Comparing sets HashSet, LinkedHashSet, TreeSet

public class Test {

    public static void main(String[] args) {

        List numbers = printAndGetList(new Integer[] { 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 2, 1 });
        Set linkedHashSet = new LinkedHashSet();
        measureTimeForSet(linkedHashSet, numbers);
        Set treeSet = new TreeSet();
        measureTimeForSet(treeSet, numbers);
        Set hashSet = new HashSet();
        measureTimeForSet(hashSet, numbers);

        System.out.println("Comparing sets:");
        System.out.println(linkedHashSet.equals(hashSet));
        System.out.println(treeSet.equals(linkedHashSet));
        System.out.println(hashSet.equals(treeSet));

        System.out.println("Comparing arrays:");
        System.out.println(Arrays.equals(linkedHashSet.toArray(), hashSet.toArray()));
        System.out.println(Arrays.equals(treeSet.toArray(), linkedHashSet.toArray()));
        System.out.println(Arrays.equals(hashSet.toArray(), treeSet.toArray()));
    }

    private static List printAndGetList(Integer[] a) {
        List list = Arrays.asList(a);
        System.out.println("List         |          | " + list);
        return list;
    }

    private static void measureTimeForSet(Set s, List numbers) {
        long start = System.nanoTime();
        for (int i = 0; i < numbers.size(); i++) {
            s.add(numbers.get(i));
            s.contains(i);
        }
        long stop = System.nanoTime();
        System.out.println(String.format("%1$-13s| %2$-6s ns| %3$s", s.getClass().getSimpleName(), stop - start, s));
    }

}


Output:

List         |          | [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 2, 1]
LinkedHashSet| 71797  ns| [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 2, 1]
TreeSet      | 137727 ns| [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
HashSet      | 30450  ns| [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16]
Comparing sets:
true
true
true
Comparing arrays:
false
false
false

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s