Thursday, September 4, 2025
HomeLanguagesJavaAbstractCollection toString() method in Java with Examples

AbstractCollection toString() method in Java with Examples

The toString() method of JavaAbstractClass is used to return a string representation of the elements of the Collection.

The String representation comprises a list representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.

Syntax:

Object.toString();

Parameter The method does not take any parameters.

Return This method returns a string representation of the collection.

Below examples illustrate the toString() method:

Example 1:




// Java program to demonstrate
// Abstract Collection toString() method
  
import java.util.*;
  
public class collection {
    public static void main(String args[])
    {
        // Creating an Empty AbstractCollection
        AbstractCollection<String> abs
            = new PriorityQueue<String>();
  
        // Use add() method
        // to add elements to the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("For");
        abs.add("Geeks");
  
        // Using toString() method
        System.out.println(abs.toString());
    }
}


Output:

[For, Geeks, To, Welcome, Geeks]

Example 2:




// Java program to demonstrate
// Abstract Collection toString() method
  
import java.util.*;
  
public class collection {
    public static void main(String args[])
    {
        // Creating an Empty AbstractCollection
        AbstractCollection<Integer> abs
            = new PriorityQueue<Integer>();
  
        // Use add() method
        // to add elements to the Collection
        abs.add(10);
        abs.add(20);
        abs.add(30);
        abs.add(40);
  
        // Using toString() method
        System.out.println(abs.toString());
    }
}


Output:

[10, 20, 30, 40]

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/AbstractCollection.html#toString–

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS