Controlling complexity is the essence of computer programming. Brian Kernigan

HashSet

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-24 11:16:26

0 Comments


Definition

HashSet is an implementation of Set Interface which does not allow duplicate value. This does not provide any guarantees for insertion order.

Character

HashSet does not allow to store duplicates.
It is not thread-safe and throw ConcurrentModificationException when the multiple thread accesses the hash set.
HashSet does not guarantee the order of insertion and is does not sort/order the entries.
HashSet tends to be fastest for lookup, insertion and deletion for larger sets.

source Code

								
package com.careerdrill.collections.set;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;

public class HashSetUse {

	public static void main(String[] args) {
		
		int []array={34,67,45,34,27,98,56};
		System.out.print("Array of elements before insert the data to HashSet: "+ Arrays.toString(array));
		
		HashSet< Integer > hash = new HashSet< Integer >();
		
		for(Integer i : array)
			hash.add(i);

		System.out.println("\nAfter insert the elements HashSet size: "+ hash.size());

		System.out.println("Validate '67' contains: "+ hash.contains(67));
		System.out.println("Validate '100' contains: "+ hash.contains(100));

	   Iterator< Integer > iterator = hash.iterator(); 
	      
	   System.out.print("HashSet elements which do not maintain insertion order: ");
	   while (iterator.hasNext()){
	   System.out.print(iterator.next() + " ");  
	   }
		   
	}

}
						

Output

    					 
Array of elements before insert the data to HashSet: [34, 67, 45, 34, 27, 98, 56]
After insert the elements HashSet size: 6
Validate '67' contains: true
Validate '100' contains: false
HashSet elements which do not maintain insertion order: 34 98 67 56 27 45
    					 
					    

Comparison

HashSet LinkedHashSet TreeSet
HashSet does not maintain insertion order LinkedHashSet maintains insertion order TreeSet provides natural sorting
HashSet allows null LinkedHashSet allows null TreeSet does not allow null
O(n) O(1) O(logn)
Implemented using hash table Implemented using doubly linked list Implemented using red block tree
Not allowed to store duplicates Not allowed to store duplicates Not allowed to store duplicates
Compare HashSet uses equals() and hashCode() methods Compare HashSet uses equals() and hashCode() methods Comparable or comparator interface implementation

When to use

When you want general purpose Set where you need to store only unique elements without any sorting or ordering requirement, you can use HashSet.

0 Comments



Please login to add comments.