Home > Java > javaTutorial > body text

How can we implement custom HashSet in Java?

王林
Release: 2023-09-03 10:01:02
forward
1381 people have browsed it

我们如何在 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
Copy after login

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>
Copy after login

Output

England
Australia
India
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template