The toArray() method of Java Set is used to form an array of the same elements as that of the Set. Basically, it copies all the element from a Set to a new array.
Syntax:
Object[] toArray()
Parameters: The method takes optional parameter. If we provide the type of Object array we want we can pass it as an argument. for ex: set.toArray(new Integer[0]) returns an array of type Integer, we can also do it as set.toArray(new Integer[size]) where size is the size of the resultant array. Doing it in the former way works as the required size is allocated internally.
Return Value: The method returns an array containing the elements similar to the Set.
Below programs illustrate the Set.toArray() method:
Program 1:
Java
// Java code to illustrate toArray() import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> abs_col = new HashSet<String>(); // Use add() method to add // elements into the Set abs_col.add( "Welcome" ); abs_col.add( "To" ); abs_col.add( "Geeks" ); abs_col.add( "For" ); abs_col.add( "Geeks" ); // Displaying the Set System.out.println( "The Set: " + abs_col); // Creating the array and using toArray() Object[] arr = abs_col.toArray(); System.out.println( "The array is:" ); for ( int j = 0 ; j < arr.length; j++) System.out.println(arr[j]); } } |
The Set: [Geeks, For, Welcome, To] The array is: Geeks For Welcome To
Program 2:
Java
// Java code to illustrate toArray() import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<Integer> abs_col = new HashSet<Integer>(); // Use add() method to add // elements into the Set abs_col.add( 10 ); abs_col.add( 15 ); abs_col.add( 30 ); abs_col.add( 20 ); abs_col.add( 5 ); abs_col.add( 25 ); // Displaying the Set System.out.println( "The Set: " + abs_col); // Creating the array and using toArray() Integer[] arr = abs_col.toArray( new Integer[ 0 ]); System.out.println( "The array is:" ); for ( int j = 0 ; j < arr.length; j++) System.out.println(arr[j]); } } |
The Set: [20, 5, 25, 10, 30, 15] The array is: 20 5 25 10 30 15
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray()