Set toArray() Method in Java (original) (raw)
Last Updated : 06 Feb, 2025
In Java, the **toArray() method is used to convert a collection to an array. It returns an array containing all the elements in the collection in the correct order.
**Example 1: Converting a Set to an Array
This is an example where a Set of String elements is converted into an array using the **toArray() method. The method returns an Object[] array.
Java `
// Java Program to demonstrates the working toArray() import java.util.*;
public class Geeks { public static void main(String args[]) {
// Creating a Set of Strings
Set<String> s = new HashSet<String>();
// Adding elements to the Set
s.add("Java");
s.add("C++");
s.add("C");
System.out.println("The Set: " + s);
// Converting the Set to an Object array
Object[] arr = s.toArray();
System.out.println("The Array is:");
for (Object obj : arr) {
System.out.print(obj + " ");
}
}
}
`
Output
The Set: [Java, C++, C] The Array is: Java C++ C
Syntax of toArray() Method
Object[] toArray();
- **Parameter: This method does not take any parameter
- **Return Type: This method returns an array of type object which contains all the elements of the collection in the correct order.
**Example 2: Converting a Set of Integers to a Specific Type Array
In this example, we use the **toArray(T[] a) method, which allows us to specify the type of the array to be returned. This avoids the need for casting when using the array.
Java `
// Converting set to an integer array import java.util.*;
public class Geeks { public static void main(String args[]) {
// Creating a Set of Integers
Set<Integer> s = new HashSet<Integer>();
// Adding elements to the Set
s.add(10);
s.add(15);
s.add(30);
s.add(20);
s.add(5);
s.add(25);
System.out.println("The Set: " + s);
// Converting the Set to an Integer array
Integer[] arr = s.toArray(new Integer[0]);
System.out.println("The Array is:");
for (Integer num : arr) {
System.out.println(num);
}
}
}
`
Output
The Set: [20, 5, 25, 10, 30, 15] The Array is: 20 5 25 10 30 15