TreeSet, SortedSet and HashSet : TreeSet « Collections Data Structure « Java






TreeSet, SortedSet and HashSet

   

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

class SetDemo {
  public static void main(String[] args) {
    String[] letters = { "A", "B", "C", "D", "E" };

    Set s = new HashSet();

    for (int i = 0; i < letters.length; i++)
      s.add(letters[i]);

    if (!s.add(letters[0]))
      System.out.println("Cannot add a duplicate.\n");

    Iterator iter = s.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());

    System.out.println("");

    SortedSet ss = new TreeSet();

    for (int i = 0; i < letters.length; i++)
      ss.add(letters[i]);

    if (!ss.add(letters[0]))
      System.out.println("Cannot add a duplicate.\n");

    iter = ss.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());
  }
}

   
    
    
  








Related examples in the same category

1.Add values to TreeSet
2.Get Synchronized Set from Java TreeSet example
3.Check if a particular value exists in Java TreeSet example
4.Copy all elements of Java TreeSet to an Object Array Example
5.Get Head Set from Java TreeSet example
6.Get lowest and highest value stored in Java TreeSet
7.Get Size of Java TreeSet
8.Get Sub Set from Java TreeSet
9.Get Tail Set from Java TreeSet
10.Iterate through elements of Java TreeSet
11.Remove all elements from Java TreeSet
12.Remove specified element from Java TreeSet
13.Sort items in a Set
14.Loop and remove element from a TreeSet
15.Creating a Sorted Set
16.Comparable with a sorted collection.
17.A TreeSet that ensures it never grows beyond a max size.