Searching...
Tuesday, 30 April 2013

Difference between HashSet ,LinkedHashSet and TreeSet

10:24

Difference between HashSet ,LinkedHashSet and TreeSet?

1. HashSet not maintaining any order ,LInkedHashSet maintaining the insertion Order ,TreeSet is maintaining the Sorting order

2. HashSet and LinkedHashSet uses equals() method in Java for comparison but TreeSet uses compareTo() method

3. HashSet and LinkedHashSet allows null values but TreeSet doesn't allow null values

Example

Here is one example to show the difference between HashSet ,LinkedHashSet and TreeSet

 

package com.vinod.test;

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

public class HashExample {
    public static void main(String[] args) {
        Set<String> hs = new HashSet<String>();
        hs.add("vinod");
        hs.add("santhosh");
        hs.add("ajay");

        Set<String> ts = new TreeSet<String>();
        ts.add("vinod");
        ts.add("santhosh");
        ts.add("ajay");

        Set<String> ls = new LinkedHashSet<String>();
        ls.add("vinod");
        ls.add("santhosh");
        ls.add("ajay");

        System.out.println("Hashset " + hs); // No order
        System.out.println("TreeSet " + ts);// Natural ordering
        System.out.println("LinkedHashSet " + ls); // Insertion order

    }

}

Output

Hashset [vinod, santhosh, ajay]

TreeSet [ajay, santhosh, vinod]

LinkedHashSet [vinod, santhosh, ajay]

Done!!! 

 

0 comments: