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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button