HashSet toString() method in Java with Example
The toString() method of Java HashSet is used to return a string representation of the elements of the Collection.
The String representation comprises a set 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:
public String 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 // HashSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty HashSet HashSet<String> abs = new HashSet<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()); } } |
[Geeks, For, Welcome, To]
Example 2:
// Java program to demonstrate // HashSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty HashSet HashSet<Integer> abs = new HashSet<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()); } } |
[20, 40, 10, 30]
Recommended Posts:
- HashSet contains() Method in Java
- HashSet add() Method in Java
- HashSet equals() method in Java with Example
- HashSet removeAll() method in Java with Example
- HashSet spliterator() method in Java
- HashSet retainAll() method in Java with Example
- HashSet toArray(T[]) method in Java with Example
- HashSet clear() Method in Java
- HashSet toArray() method in Java with Example
- HashSet containsAll() method in Java with Example
- HashSet clone() Method in Java
- HashSet hashCode() method in Java with Example
- HashSet size() Method in Java
- HashSet remove() Method in Java
- HashSet iterator() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



