This example demonstrates how to copy all elements of a HashSet object to an array of Objects with toArray method in Java.
Source Code
package com.beginner.examples;
import java.util.HashSet;
public class CopyHashSetToObjectArrayExample {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
//Add elements
hashSet.add("A");
hashSet.add("B");
hashSet.add("C");
hashSet.add("D");
//The collection is converted to an Object array using the
//toArray() method in the HashSet class
Object[] elementsObj = hashSet.toArray();
for(Object o:elementsObj)
{
System.out.println(o);
}
}
}
Output:
D
A
B
C
References
Imported packages in Java documentation: