Java Vector toString() Method

Java Vector Java Vector


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:

  1. The string starts with a left square bracket[[
  2. then the string representations of all elements, using commas,and spaces to separate them
  3. finally ends with a right square bracket]]

Internal Implementation

This method actually calls the `toString()` implementation of the `AbstractCollection` class, which:
  1. uses an iterator to traverseVectorall elements in it
  2. calls thetoString()method of each element
  3. concatenates these strings", "together
  4. adds brackets at the outermost layer[and]

Usage Examples

Basic Example

Example

import java.util.Vector;

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

import java.util.Vector;

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

Vector<String> vectorWithNull = new Vector<>();
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

class Person {
    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

class Person {
    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=&#39;Alice&#39;, age=25}, Person{name=&#39;Bob&#39;, age=30}]

Difference from Arrays.toString()

AlthoughVectoroftoString()andArrays.toString()both return a similar string format, they have the following differences:

  1. Different applicable objects:

    • Vector.toString(): used forVectorcollections
    • Arrays.toString(): used for arrays
  2. Different implementation methods:

    • Vector.toString(): implemented based on iterators
    • Arrays.toString(): directly accesses array elements
  3. Performance Considerations:

    • For large collections,Vector.toString()there may be additional iteration overhead

Practical Application Scenarios

1. Debugging and Logging

The `toString()` method is often used to quickly inspect the contents of a `Vector` during debugging:

Example

Vector<Integer> numbers = getNumbersFromSomewhere();
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

Vector<String> options = getMenuOptions();
JOptionPane.showMessageDialog(null, "Available options: " + options.toString());

3. Combining with Other String Operations

Example

Vector<String> words = new Vector<>(Arrays.asList("Hello", "World", "Java"));
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:

  1. Memory usage: for very largeVector, the generated string may occupy a large amount of memory
  2. Time overhead: need to traverse the entireVectorto construct the string

For performance-sensitive scenarios, you can consider:

  1. outputting only some elements
  2. usingStringBuildercustom output formats
  3. For logging, use the lazy evaluation feature of the logging framework

Summary

VectoroftoString()The method is a simple but practical tool that:

  1. provides a quickVectorand convenient way to view the contents
  2. returns a uniformly formatted string representation
  3. automatically handles elements of various types
  4. is a great helper for debugging and simple output

Understanding and using this method appropriately can greatly improve development efficiency and code readability.

Java Vector Java Vector

Other Extensions