How to Copy All LinkedHashSet Elements to Array in Java


This example will introduce how to copy all elements of LinkedHashSet object to an array of Objects with toArray method in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedHashSet;

public class CopyElementsOfHashSetToArray {

	public static void main(String[] args) {
		
		//create LinkedHashSet.
		LinkedHashSet linkedHashSet = new LinkedHashSet();
		
		linkedHashSet.add("A");
		linkedHashSet.add("B");
		linkedHashSet.add("C");
		linkedHashSet.add("D");
		
		/*
		 * To copy all elements of java LinkedHashSet object into array use Object[] toArray() method.
		 */
		Object[] ObjectArray = linkedHashSet.toArray();
		
		System.out.println("Copy complete, the Array contains :");
		for(int index=0; index < ObjectArray.length ; index++) {
			System.out.println(ObjectArray[index]);
		}
	}

}

Output:

Copy complete, the Array contains :
A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments