Java HashSet

Profile picture for user arilio666

HashSet is a Java class that implements the Set interface from the Java Collections Framework. It stores an unordered collection of elements where duplicate elements are not permitted. Assuming a vital hash function and load factor, HashSet uses hashing to keep elements and performs constant time for fundamental operations such as add, remove, and contain.

HashSet Features

  • HashSet does not permit duplicate elements. It will not be added if you try to add an existing element to the set.
  • The elements in a HashSet are kept unordered, which means there is no guarantee of element order. Other classes, such as LinkedHashSet or TreeSet, can be used to retain a particular order.
  • HashSet allows for the storage of null values, but only once. When you add null to a HashSet, it is considered a single element.
  • HashSet is supported by a hash table, which allows for efficient look-up, insertion, and deletion operations. However, HashSet's performance can only improve if the load factor is lowered.
  • HashSet is not thread-safe, which means it does not provide synchronization techniques for concurrent access. If you need to use HashSet in a multi-threaded environment, employ synchronization mechanisms such as explicit synchronization or contemporary collections.
  • HashSet supports efficient iteration over its elements via the Iterator interface, allowing you to iterate over the set's elements in any order.

Example:

package week1.day2;
import java.util.HashSet;
import java.util.Set;
public class Calculator {
    public static void main(String[] args) {
        Set<String> devilFruits = new HashSet<>();
        devilFruits.add("Gum Gum Fruit");
        devilFruits.add("Logia");
        devilFruits.add("Paramecia");
        devilFruits.add("Mera Mera No Mi");
        devilFruits.add("Gum Gum Fruit");
        System.out.println("HashSet: " + devilFruits);
        devilFruits.remove("Logia");
        System.out.println("HashSet after removal: " + devilFruits);
        System.out.println("Contains 'Mera Mera No Mi': " + devilFruits.contains("Mera Mera No Mi"));
        System.out.println("Size of HashSet: " + devilFruits.size());
        for (String fruit : devilFruits) {
            System.out.println(fruit);
        }
    }
}
  • Here we created HashSet and added some devilFruits using the add method.
  • We tried to add duplicate Gum-Gum Fruit, which will be ignored.
  • Using contains, we got the boolean response.
  • We then used size to get the size of the devilFruits.
  • Then using advanced for loop, we printed the fruits.

Output:

HashSet: [Paramecia, Mera Mera No Mi, Gum Gum Fruit, Logia]
HashSet after removal: [Paramecia, Mera Mera No Mi, Gum Gum Fruit]
Contains 'Mera Mera No Mi': true
Size of HashSet: 3
Paramecia
Mera Mera No Mi
Gum Gum Fruit
Tags