Compare HashSet,TreeSet and ArrayList by Example


import java.util.*;
import java.math.*;
public class NoDupsTest
{
  /* ---- HashSet approach (list order not maintained) ---- */
  public static void test_HashSet(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    HashSet h = new HashSet(a);
    a.clear();
    a.addAll(h);
    long diff = System.currentTimeMillis()-cur;
    System.out.println("HashSet approach (no order) = "+diff);
  }
 
  /* ---- TreeSet approach (list order not maintained, but sorted) ---- */
  public static void test_TreeSet(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    TreeSet t = new TreeSet(a);
    a.clear();
    Iterator iter = t.iterator();
    while (iter.hasNext())
      a.add(iter.next());
    long diff = System.currentTimeMillis()-cur;
    System.out.println(
      "TreeSet approach (sorted order) = "+diff+" ms");
  }
 
  /* ---- ArrayList and HashSet approach (order maintained) ---- */
  public static void test_HashSet_listOrder(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    Set set = new HashSet();
    List newList = new ArrayList();
    for (Iterator iter = a.iterator(); iter.hasNext(); ) {
      Object element = iter.next();
      if (set.add(element))
        newList.add(element);
    }
    a.clear();
    a.addAll(newList);
    long diff = System.currentTimeMillis()-cur;
    System.out.println(
      "ArrayList/HashSet approach (list order) = "+diff+" ms");
  }
 
  /* ---- ArrayList and TreeSet approach ---- */
  public static void test_TreeSet_listOrder(ArrayList a_master)
  {
    ArrayList a = new ArrayList(a_master);
    long cur = System.currentTimeMillis();
    Set set = new TreeSet();
    List newList = new ArrayList();
    for (Iterator iter = a.iterator(); iter.hasNext(); ) {
      Object element = iter.next();
      if (set.add(element))
        newList.add(element);
    }
    a.clear();
    a.addAll(newList);
    long diff = System.currentTimeMillis()-cur;
    System.out.println(
      "ArrayList/TreeSet approach (list order) = "+diff+" ms");
  }
 
  public static void main(String[] args)
  {
    int num = Integer.parseInt(args[0]);
    int numUnique = Integer.parseInt(args[1]);
    /* Create master list */
    Random rnd = new Random();
    ArrayList masterList = new ArrayList();
    for (int i=0; i<num; i++) {
      masterList.add(new Integer((Math.abs(rnd.nextInt())%numUnique)));
    }
    /* Run tests */
    test_HashSet(masterList);
    test_TreeSet(masterList);
    test_HashSet_listOrder(masterList);
    test_TreeSet_listOrder(masterList);
  }
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|