Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JAVA Set and Hashset

Set

  • • Set is a child interface of Collection.
  • • When we want to represent a group of individual data items as a single entity where duplicates are not allowed and insertion order is not preserved, then we should go to the collection Set.
  • • Set interface does not contain any new method, so we have to use only Collection interface methods.

HashSet

  • • It is an implementation class of Set interface.
  • • Underlying data structure is HashTable.
  • • Duplicates are not allowed. If we are trying to insert duplicates, we will not get any compile-time error or run time error. Simply the add() method returns a boolean value that is false.
  • • Insertion order is not preserved and all data items will be inserted based on hash code of data items.
  • • Heterogeneous data items are allowed.
  • • Null insertion is possible.
  • • Implements Serializable and Clonable interface.
  • • Not implements RandomAccess interface.
  • • If our frequent operation is the searching operation, then HashSet is the best choice as Collection with the help of hash code of data items.

Constructors

    HashSet h=new HashSet();

  • • Creates an empty HashSet with default initial capacity 16 and the fill ratio / load factor is 0.75(75%).
  • HashSet h=new HashSet(int initial capacity);

  • • Create an empty HashSet by taking given initial capacity. Here load factor is also 0.75.
  • HashSet h=new HashSet(int initial capacity, float load factor);

  • • Create an empty HashSet by taking given initial capacity and given load factor.
  • HashSet h=new HashSet(Collection c);

  • • By taking any Collection object, we can create an equivalent HashSet object. Let's see a simple demo program on HashSet.
HashSetDemo.java
import java.util.*;
class HashSetDemo
{
	public static void main(String[] args)
	{
		HashSet h=new HashSet();

		h.add("Dibya");
		h.add("Dibakar");
		h.add("Jyoti");
		h.add("Renuka");

		System.out.println(h.add("Dibya"));
		System.out.println(h);

		Iterator it=h.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}

	}
}

Output

img

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext