Master java skills

HashSet in java

HashSet stores only unique elements. No duplicates are allowed unlike List. Below is the hierarchy of Set interface in collections framework

HashSet

One of the implementation class of Set interface is HashSet. It stores elements using a mechanism called hashing. Below are some important features of hash set.

  1. Stores only unique elements
  2. Uses hashing technique to store elements
  3. It allows one null value
  4. Doesn’t maintain insertion order of elements
  5. elements are stored according to their hash codes
  6. Initial capacity is 16 with load factor 0.75

Creating and iterating over HashSet

In the below example, we are adding some duplicate elements, but hash set will keep only a single copy of duplicate element.

package com.javatrainingschool;

import java.util.HashSet;
import java.util.Set;

public class HashSetExample {

	public static void main(String[] args) {
		
		Set<Integer> set = new HashSet<Integer>();
		
		set.add(100);
		set.add(300);
		set.add(400);
		set.add(300);
		set.add(500);
		set.add(500); 
		
		System.out.println("Size of the set is : " + set.size());
		
		for(int value : set) {
			System.out.println(value);
		}
	}
}
Output :
Size of the set is : 4
400
100
500
300

Remove methods in Set

//Below method will remove the specified object
public boolean remove(Object o);

boolean removeAll(Collection<?> c);

//Below method will clear the HashSet
public void clear();

Contains method in HashSet

This method checks if the passed object exist in the hashset or not. Below is the syntax

public boolean contains(Object o);