Sunday, 27 April 2014

TreeSet : toArray: Copy Set Data to Object Array

Object[] toArray()
Returns an array containing all of the elements in this set. The order how the Elements from the set copied is totally depends on the iterator implementation.

import java.util.*;
class TreeSetCopyToArray{
 public static void main(String args[]){
  TreeSet<Double> mySet = new TreeSet<> ();
  Object myArray[];
  
  /* Add Elements to the Set */
  mySet.add(55.6);
  mySet.add(10.01);
  mySet.add(5.01);
  mySet.add(-100.123);
  
  /* Copy Elements to the myArray */
  myArray = mySet.toArray();
  
  /* Display the elements of the Array */
  System.out.println("Elements in the Array are");
  for(Object obj : myArray)
   System.out.println(obj);
 }
}

Output
Elements in the Array are
-100.123
5.01
10.01
55.6

Observe the Output, the Elements are not copied to the “myArray” as the way they inserted. Elements are copied to the Array based on the iterator.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment