Java Collections

HashSet class in collection

A HashSet is a collection set that neither allows duplicate elements nor order or position its elements. This class implements the Set interface and extends AbstractSet. It creates a collection that uses a hash table for storage. Hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as an index at which the data associated with the key is stored. The transformation of key into its hash code is performed automatically. HashSet is not synchronized. It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. 

Constructor in HashSet:
The HashSet class supports four constructors. The first form constructs a default hash set:

HashSet( );
//The following constructor form initializes the hash set by using the elements of c.
HashSet(Collection c);

//The following constructor form initializes the capacity of the hash set to capacity.
//The capacity grows automatically as elements are added to the Hash.
HashSet(int capacity);

//The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its //arguments:
HashSet(int capacity, float fillRatio);
/*Here the fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded*/

Methods in HashSet:
Apart from the methods inherited from its parent classes, HashSet defines following methods:

SN Methods with Description
1 boolean add(Object o)
Adds the specified element to this set if it is not already present.
2 void clear()
Removes all of the elements from this set.
3 Object clone()
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
4 boolean contains(Object o)
Returns true if this set contains the specified element
5 boolean isEmpty()
Returns true if this set contains no elements.
6 Iterator iterator()
Returns an iterator over the elements in this set.
7 boolean remove(Object o)
Removes the specified element from this set if it is present.
8 int size()
Returns the number of elements in this set (its cardinality).

Example:
The following program illustrates several of the methods supported by HashSet:

import java.util.*;
public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      System.out.println(hs);
   }
}

Output:

Example Duplicate Value adding to HashSet:
The following program illustrates several of the methods supported by HashSet:

import java.util.*;
public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("B");
      hs.add("E");
      hs.add("F");
      hs.add("F");
      System.out.println(hs);
   }
}

Output:

Adding User Define Object to the HashSet:
To understand the duplication with objects see the below example.

The Person class has the attributes as age and name. and the class has getter/setter methods of its attributes, and the equals and hashCode method has been overridden in order to check the equality of attributes.

import java.util.HashSet;
 
public class HashSetExample {
    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<Person>();
        set.add(new Person(27, "DINESH"));
        set.add(new Person(27, "DINESH"));
        set.add(new Person(24, "SWEETY"));
        set.add(new Person(24, "ANAMIKA"));
        set.add(new Person(24, "ANAMIKA"));
        System.out.println("The size of set of person is : " + set.size());
        System.out.println("The elements of set of person is : " + set);
    }
}
 
class Person {
    int age;
    String name;
 
    public Person(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
 
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
   
   public String toString(){
 return "n Person {name: "+this.name+" age: "+this.age+"}";
   }
}

output:

Please note this HashSet implementation is not synchronized, To get the synchronized set you should use the Collections utility class method as. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSet() method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

Set s = Collections.synchronizedSet(new HashSet(...));

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago