HashSet implements the Set interface, which does not allow duplicate values . HashSetis not synchronized and is not thread-safe. When we can add any duplicate elements to the HashSet, the add() method returns false and does not allow duplicate elements to be added to the HashSet.
Syntax
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
In the following example, we can implement a customized HashSet.
import java.util.*; public class CustomHashSetTest extends AbstractSet<object> { 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<object> iterator() { return map.keySet().iterator(); } @Override public int size() { return map.size(); } } </object></object>
England Australia India
The above is the detailed content of How can we implement custom HashSet in Java?. For more information, please follow other related articles on the PHP Chinese website!