Here we will see how to define custom HashSet in Java. We will define add() method.
- Define a class which extends AbstractSet<Object> and override all methods.
- Define HashMap reference.
private HashMap<Object,Object> hashMapReference = null;
- Create an object of the Object class.
private static final Object dummyObject = new Object();
- Define default constructor and initialize HashMap reference inside this default constructor.
public CustomHashSet() { hashMapReference = new HashMap<>(); }
- Define the add() method.
public boolean add(Object object) { return hashMapReference.put(object, dummyObject)==null; }
Let’s integrate the code snippet.
package customhashset; import java.util.*; public class CustomHashSet extends AbstractSet<Object> { private HashMap<Object,Object> hashMapReference = null; private static final Object dummyObject = new Object(); public CustomHashSet() { hashMapReference = new HashMap<>(); } public boolean add(Object object) { return hashMapReference.put(object, dummyObject)==null; } public static void main(String[] args) { CustomHashSet hashSetObj = new CustomHashSet(); hashSetObj.add("ram"); hashSetObj.add("mohan"); hashSetObj.add("sohan"); hashSetObj.add("ram"); for(Object object : hashSetObj) { System.out.println(object.toString()); } } @Override public Iterator<Object> iterator() { return hashMapReference.keySet().iterator(); } @Override public int size() { return hashMapReference.size(); } }
Output is –
sohan
mohan
ram