Java – Hashset class

Previous
Next

Set interface: Implementations are

  1. HashSet
  2. LinkedHashSet
  3. TreeSet

Note : HashSet & LinkedHashSet stores the data into collection Object according to HashTable algorithm.

How the elements store into HashTable ?

  • Every Hash table has a fixed size by default.
  • The size may varies depends on number of elements stored in the Collection.
  • Hash table implementation is bit advanced to linked list representation.
  • In Hashtable also, elements will be stored in the form of nodes only.
  • Searching of element is faster than Linkedlist in Hashtable.

HashSet :

  • available in util package.
  • since from jdk 1.2
  • not ordered
  • not allowed duplicates.
  • initial capacity  is 16
  • default load factor is 0.75
  • HashSet is not Synchronized by default, can be synchronized explicitly as follows…
    • Collections.synchronizedSet(new HashSet(….));     

ArrayList is an ordered collection. Hence the elements will be displayed in the insertion order only.

import java.util.*;
class Demo 
{
	public static void main(String[] args) 
	{
		ArrayList list = new ArrayList();
		for (int i=10 ; i<=50 ; i=i+10)
		{
			list.add(i);
		}
		System.out.println("List is : " + list);
	}
}

HashSet is not ordered. The following code snippet explains clearly.

import java.util.*;
class Demo 
{
	public static void main(String[] args) 
	{
		HashSet set = new HashSet();
		for (int i=10 ; i<=50 ; i=i+10)
		{
			set.add(i);
		}
		System.out.println("Set is : " + set);
	}
}
  • ArrayList allow duplicates.
  • Random class generates the random values from 0 to specified bound.
  • The following code generates duplicates values as we have given low bound value and store those elements into ArrayList object.
import java.util.*;
class Demo 
{
	public static void main(String[] args) 
	{
		Random rand = new Random();
		ArrayList list = new ArrayList();
		for (int i=1 ; i<=10 ; i++)
		{
			int ele = rand.nextInt(5); // generate value from 0 - 4
			list.add(ele);
		}
		System.out.println("List is : " + list);
	}
}
  • Set doesn’t allow duplicates.
  • We can construct one collection from another collection object.
  • If we construct Set from List, all the duplicates will be removed automatically.
import java.util.*;
class Demo 
{
	public static void main(String[] args) 
	{
		Random rand = new Random();
		ArrayList list = new ArrayList();
		for (int i=1 ; i<=10 ; i++)
		{
			int ele = rand.nextInt(5);
			list.add(ele);
		}
		System.out.println("List is : " + list);

		HashSet set = new HashSet(list);
		System.out.println("Set is : " + set);
	}
}
Previous
Next

Add Comment

Courses Enquiry Form