Java HashSet toArray() Method
Example
Get an array from a set:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Object[] carsArray = cars.toArray();
for (Object item : carsArray) {
System.out.println(item);
}
}
}
Definition and Usage
The toArray() method returns an array with all the items in the set.
Without an argument, it returns an Object array. If you give it an array of the right type, like String[], it returns an array of that type (see More Examples below).
Syntax
One of the following:
public Object[] toArray()
public T[] toArray(T[] array)
T refers to the data type of items in the set.
Parameter Values
| Parameter | Description |
|---|---|
| array | Optional. An array of the same type as the items in the set. If it is big enough, the items are stored in it. If not, a new array of the same type is created. |
Technical Details
| Returns: | An array with all the items in the set. |
|---|
More Examples
Example
Get a String array from a set:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
String[] carsArray = new String[cars.size()];
carsArray = cars.toArray(carsArray);
for (String item : carsArray) {
System.out.println(item);
}
}
}