Wednesday, April 21, 2010

HashSet with Example


If your requirement is frequent insert then we go with HashSet.

For efficiency objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation of the Object.

It is generally faster to add elements to the HasSet then convert the collection to a TreeeSet for sorted traversal.

To optimize HashSet space usage , you can tune initial capacity and load factor.

Example:

public class HashSetExample {

    public static void main(String[] args) {

        HashSet<String> hs=new HashSet<String>();

        // duplicate element is not permitted
        hs.add("b");
        hs.add("a");
        hs.add("c");
        hs.add("d");
        hs.add("d");

        Iterator it=hs.iterator();

        while(it.hasNext())
        {
            String value =(String)it.next();

            System.out.println("Value :"+value);
        }

        System.out.println("Size :"+hs.size());

        hs.remove("d");

        hs.clear();
    }
}

No comments: