HashSet概况:

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable

HashSet源码:

常量:

transient HashMap<E,Object> map;  // HashSet底层实现就是HashMap 
private static final Object PRESENT = new Object(); // 这个PRESENT相当于HashMap中的value值

构造方法:

public HashSet() {
    map = new HashMap<>();
}
    
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}
    
public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}

 add(E e):通过 map.put() 方法来添加元素,该方法如果新插入的key不存在,则返回null,如果新插入的key存在,则返回原key对应的value值(注意新插入的value会覆盖原value值)。

     也就是说 HashSet 的 add(E e) 方法,会将 e 作为 key,PRESENT 作为 value 插入到 map 集合中,如果 e 不存在,则插入成功返回 true;如果存在,则返回false。

public boolean add(E e) {            
    return map.put(e, PRESENT)==null;
}                                    

HashSet对象重复问题以及hashCode(),equal()方法:

关于set对象里面的重复:

class Person {
    private String name;
    private int age;
        ...... 
}
public class SetTest {
    public static void main(String[] args) {
        Set<Person> set = new HashSet<>();
        set.add(new Person("张三", 14));
        set.add(new Person("李四", 16));
        set.add(new Person("张三", 14));
        set.add(new Person("李四", 16));
        set.add(new Person("张三", 14));
        System.out.println(set);
    }
}
View Code

相关文章:

  • 2021-06-03
  • 2021-05-29
  • 2021-11-02
  • 2021-06-02
  • 2021-08-28
猜你喜欢
  • 2021-08-08
  • 2021-07-27
  • 2022-12-23
  • 2021-11-05
  • 2021-10-06
相关资源
相似解决方案