Bright Java Tutorial

is brought to you by DoITBright LLC

Java

Popular Java Set Implementations

The java.util.Set is an interface from the Collection API. It can grow its size and typically allows at most one null value and does not allow duplicates. The most popular classes that implements the Set are java.util.HashSet, java.util.TreeSet and java.util.LinkedHashSet. Let us look at the example code below and observe their similarities and differences.

  package com.example.core;

  import java.util.HashSet;
  import java.util.Iterator;
  import java.util.LinkedHashSet;
  import java.util.TreeSet;

  /**
   * This is to demonstrate how to use a Set. Set does not 
   * allow duplicate elements. If you create a set of 
   * String with value "a", "b", "b" only "a","b" will 
   * exist since the duplicate "b" will be removed 
   * automatically.
   * 
   * @author Rolan Liwanag
   *
   */
  public class HashSetVsTreeSetVsLinkedHashSet {

    public static void main(String[] args) {
      HashSet hSet = new HashSet();
      hSet.add(40);
      hSet.add(30);
      hSet.add(20);
      hSet.add(30);
      Iterator ihSet = hSet.iterator();
      while(ihSet.hasNext()) {
        Integer value = ihSet.next();
        System.out.println("HashSet value " + value);
      }
      /*
       * A HashSet is the fastest among the implementation 
       * of the Set interface. It does not guarantee any 
       * sort order.
       */
      TreeSet tSet = new TreeSet();
      tSet.add(40);
      tSet.add(30);
      tSet.add(20);
      tSet.add(30);
      Iterator itSet = tSet.iterator();
      while(itSet.hasNext()) {
        Integer value = itSet.next();
        System.out.println("TreeSet value " + value);
      }
      /*
       * A TreeSet guarantees the order of its elements in 
       * ascending order. It is slower compared to HashSet.
       */
      LinkedHashSet lhSet 
        = new LinkedHashSet();
      lhSet.add(40);
      lhSet.add(30);
      lhSet.add(20);
      lhSet.add(30);
      Iterator ilhSet = lhSet.iterator();
      while(ilhSet.hasNext()) {
        Integer value = ilhSet.next();
        System.out.println("LinkedHashSet value " + value);
      }
      /*
       * A LinkedHashSet guarantees the order of insertion.
       * Its speed is in between HashSet and TreeSet.
       */
    }
  }
                            



Back    Next