How to Copy All Elements of HashSet into Object Array in Java


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:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments