AbstractCollection toString() Method in Java
In Java, the toString() method is defined in the Object class and is inherited by all the Java classes. It is used to return a string representation of an object. The AbstractCollection class is a part of the Java Collections Framework, which overrides this method to provide a string representation of the collection.
Example 1: This example demonstrates how the toString() method of AbstractCollection returns a string representation of the collection's elements.
// Java program to demosntrates
// how toString() method works
import java.util.*;
public class Geeks {
public static void main(String[] args) {
AbstractCollection<String> ac = new ArrayList<>();
ac.add("Geeks");
ac.add("for");
ac.add("Geeks");
System.out.println(ac.toString());
}
}
Output
[Geeks, for, Geeks]
Syntax of toString() Method
public String toString()
- Parameter: The method does not take any parameters.
- Return Type: This method returns a string representation of the collection.
Example 2: This example demonstrates the working of toString() method.
// Java program to demonstrate
// Abstract Collection toString() method
import java.util.*;
public class Geeks {
public static void main(String[] args) {
AbstractCollection<Integer> ac = new ArrayList<>();
ac.add(10);
ac.add(20);
ac.add(30);
ac.add(40);
System.out.println(ac.toString());
}
}
Output
[10, 20, 30, 40]