How to Copy All Elements of Java TreeSet into Array


Here we can see how to copy all elements of TreeSet object to an array of Objects with toArray method in Java.

Source Code

package com.beginner.examples;

import java.util.TreeSet;

public class CopyElementsOfTreeSetToArray {

	public static void main(String[] args) {
		
		//create TreeSet.
		TreeSet treeSet = new TreeSet();
		
		treeSet.add("A");
		treeSet.add("B");
		treeSet.add("C");
		treeSet.add("D");
		
		/*
		 * To copy all elements of java TreeSet object into array using toArray() method of TreeSet.
		 */
		Object[] objArray = treeSet.toArray();
		
		System.out.println("Copy complete. Array Contains ");
		
		for(int index=0; index < objArray.length ; index++) {
			System.out.println(objArray[index]);
		}

	}

}

Output:

Copy complete. Array Contains 
A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments