Home >Java >javaTutorial >How can we implement custom HashSet in Java?

How can we implement custom HashSet in Java?

王林
王林forward
2023-09-03 10:01:021414browse

我们如何在 Java 中实现自定义 HashSet?

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.

Example

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>

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete