Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we implement a Custom HashSet in Java?
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
Advertisements