Java Vector toString() Method
toString()is a built-in method in JavaVectorof the class, used to return the string representation of the vector (Vector). This method is inherited fromAbstractCollectionthe class, and isVectoroverridden by the class to achieve a specific string representation.
Method Syntax
public String toString()
Return Value
Returns a string representing all elements in the `Vector` collection.Method Details
VectoroftoString()The method returns a string in the following format:
- The string starts with a left square bracket
[[ - then the string representations of all elements, using commas
,and spacesto separate them - finally ends with a right square bracket
]]
Internal Implementation
This method actually calls the `toString()` implementation of the `AbstractCollection` class, which:- uses an iterator to traverse
Vectorall elements in it - calls the
toString()method of each element - concatenates these strings
", "together - adds brackets at the outermost layer
[and]
Usage Examples
Basic Example
Example
public class VectorToStringExample {
public static void main(String[] args) {
// Create a Vector
Vector<String> fruits = new Vector<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Use the toString() method
String vectorString = fruits.toString();
System.out.println(vectorString);
}
}
Output
[Apple, Banana, Orange]
Example with Different Types of Elements
Example
public class MixedVectorToString {
public static void main(String[] args) {
Vector<Object> mixedVector = new Vector<>();
mixedVector.add("String");
mixedVector.add(123);
mixedVector.add(45.67);
mixedVector.add(true);
System.out.println(mixedVector.toString());
}
}
Output
[String, 123, 45.67, true]
Notes
1. Element Order
The order of elements in the string returned by the `toString()` method is the same as their order in the `Vector`, because `Vector` is an ordered collection.2. When Elements Are null
If the `Vector` contains `null` elements, they will be converted to the string `"null"`:Example
vectorWithNull.add("First");
vectorWithNull.add(null);
vectorWithNull.add("Last");
System.out.println(vectorWithNull.toString());
Output
[First, null, Last]
3. Handling Custom Objects
For custom class objects, the `toString()` method calls that object's `toString()` method. If the custom class does not override `toString()`, the default implementation of the `Object` class is used.Example
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class CustomObjectToString {
public static void main(String[] args) {
Vector<Person> people = new Vector<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 30));
System.out.println(people.toString());
}
}
Output (without overriding toString())
[Person@15db9742, Person@6d06d69c]
Improved Person class
Example
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
Improved output
[Person{name='Alice', age=25}, Person{name='Bob', age=30}]
Difference from Arrays.toString()
AlthoughVectoroftoString()andArrays.toString()both return a similar string format, they have the following differences:
Different applicable objects:
Vector.toString(): used forVectorcollectionsArrays.toString(): used for arrays
Different implementation methods:
Vector.toString(): implemented based on iteratorsArrays.toString(): directly accesses array elements
Performance Considerations:
- For large collections,
Vector.toString()there may be additional iteration overhead
- For large collections,
Practical Application Scenarios
1. Debugging and Logging
The `toString()` method is often used to quickly inspect the contents of a `Vector` during debugging:Example
System.out.println("Current vector contents: " + numbers.toString());
2. Simple Data Display
Used when you need to simply display the contents of a `Vector`:Example
JOptionPane.showMessageDialog(null, "Available options: " + options.toString());
3. Combining with Other String Operations
Example
String sentence = words.toString()
.replace("[", "")
.replace("]", "")
.replace(",", "");
System.out.println(sentence); // Output: Hello World Java
Performance Considerations
AlthoughtoString()the method is very convenient, but when dealing with largeVectoryou need to pay attention to:
- Memory usage: for very large
Vector, the generated string may occupy a large amount of memory - Time overhead: need to traverse the entire
Vectorto construct the string
For performance-sensitive scenarios, you can consider:
- outputting only some elements
- using
StringBuildercustom output formats - For logging, use the lazy evaluation feature of the logging framework
Summary
VectoroftoString()The method is a simple but practical tool that:
- provides a quick
Vectorand convenient way to view the contents - returns a uniformly formatted string representation
- automatically handles elements of various types
- is a great helper for debugging and simple output
Understanding and using this method appropriately can greatly improve development efficiency and code readability.
Other Extensions
Java Vector