How can we implement a Custom HashSet in Java?

JavaObject Oriented ProgrammingProgramming

A HashSet implements Set interface which does not allow duplicate values. A HashSet is not synchronized and is not thread-safe. When we can add any duplicate element to a HashSet, the add() method returns false and does not allow to add a duplicate element to HashSet.

Syntax

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

In the below example, we can implement a Custom HashSet.

Example

import java.util.*;
public class CustomHashSetTest extends AbstractSet {
   private HashMap<Object, Object> map = null;
   private static final Object tempObject = new Object();
   public CustomHashSetTest() {
      map = new HashMap<>();
   }
   public boolean add(Object object) {
      return map.put(object, tempObject)==null;
   }
   public static void main(String[] args) {
      CustomHashSetTest test = new CustomHashSetTest();
      test.add("India");
      test.add("Australia");
      test.add("England");
      test.add("Australia");
      for(Object object : test) {
         System.out.println(object.toString());
      }
   }
   @Override
   public Iterator iterator() {
      return map.keySet().iterator();
   }
   @Override
   public int size() {
      return map.size();
   }
}

Output

England
Australia
India
raja
Published on 08-Aug-2020 12:34:35
Advertisements