Java中的向量 toString() 方法与示例
Java.util.Vector.toString() 是 Vector 的内置方法,用于获取 Vector 对象的字符串表示形式,其形式为由“,”分隔的条目的字符串表示形式。所以基本上 toString() 方法用于将 Vector 的所有元素转换为 String。
句法:
Vector.toString()
参数:该方法不带任何参数。
返回值:该方法返回由 Vector 元素的字符串表示形式组成的字符串表示形式。
下面的程序说明了Java.util.Vector.toString() 方法的工作:
方案一:
Java
// Java code to illustrate the toString() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating vector type object
Vector vector = new Vector();
// Inserting elements into the table
vector.add("Geeks");
vector.add("4");
vector.add("Geeks");
vector.add("Welcomes");
vector.add("You");
// Displaying the Vector
System.out.println("Vector: " + vector);
// Displaying the string representation
System.out.println("The String representation is: "
+ vector.toString());
}
}
Java
// Java code to illustrate the toString() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating an empty Vector
Vector vector
= new Vector();
// Inserting elements into the table
vector.add(10);
vector.add(15);
vector.add(20);
vector.add(25);
vector.add(30);
// Displaying the Vector
System.out.println("Initial Vector is: " + vector);
// Displaying the string representation
System.out.println("The String representation is: "
+ vector.toString());
}
}
输出:
Vector: [Geeks, 4, Geeks, Welcomes, You]
The String representation is: [Geeks, 4, Geeks, Welcomes, You]
方案二:
Java
// Java code to illustrate the toString() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating an empty Vector
Vector vector
= new Vector();
// Inserting elements into the table
vector.add(10);
vector.add(15);
vector.add(20);
vector.add(25);
vector.add(30);
// Displaying the Vector
System.out.println("Initial Vector is: " + vector);
// Displaying the string representation
System.out.println("The String representation is: "
+ vector.toString());
}
}
输出:
Initial Vector is: [10, 15, 20, 25, 30]
The String representation is: [10, 15, 20, 25, 30]