In this section, we will learn what the Set toArray() method is and how to use it in Java.
What is Java Set toArray() Method?
The Java Set toArray() method is used to get an array representation of a Set object.
Note: this returned array has its own copy of the target Set object. This means changing the value in the array or in the Set object won’t affect the elements of the other.
Also, the order of the elements is preserved in the returned array.
Java Set toArray() Method Syntax:
Object[] toArray()
toArray() Method Parameters:
The method does not take an argument.
toArray() Method Return Value:
The return value of this method is an array object that contains the elements of the target Set object.
toArray() Method Exceptions:
The method does not throw an exception.
Example: using Set toArray() method
import java.util.Set; import java.util.HashSet; public class Main { public static void main(String[] args){ Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); set.add(6); set.add(7); Object array[] =set.toArray(); for (Object i: array){ System.out.println((int)i); } } }
Output:
1 2 3 4 5 6 7