TreeSet
Convert TreeSet to Object array example
This is an example of how to convert a TreeSet to an Object array in Java. Converting a TreeSet to an Object array implies that you should:
- Create a new TreeSet.
- Populate the set with elements, with
add(E e)
API method of TreeSet. - Create a new object array, using the
toArray()
API method of TreeSet. The method returns an array containing all of the elements in the set. It must allocate a new array. The caller is thus free to modify the returned array.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.TreeSet; public class TreeSetToArrayExample { public static void main(String[] args) { // Create a TreeSet and populate it with elements TreeSet treeSet = new TreeSet(); treeSet.add("element_1"); treeSet.add("element_2"); treeSet.add("element_3"); // Object[] toArray() method returns an array containing all of the elements in this set Object[] objArray = treeSet.toArray(); System.out.println("Elements in Array :"); for(int i=0; i < objArray.length ; i++) System.out.println(objArray[i]); } }
Output:
Elements in Array :
element_1
element_2
element_3
This was an example of how to convert a TreeSet to an Object array in Java.