首先创建一个学生类
class Student{ String id; public Student(String id) { this.id = id; } }
然后向HashSet集合存储学生类型的对象:
HashSet<Student>set = new HashSet<>(); set.add(new Student("1")); set.add(new Student("1"));
分析底层代码:
public boolean add(E e) { return map.put(e, PRESENT)==null; }
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p;
分析HashSet集合存储自定义类型对象的存储过程
最新推荐文章于 2022-05-24 12:45:58 发布
本文详细分析了HashSet如何存储自定义类型对象,解释了为何需要重写hashCode和equals方法。通过实例展示了不重写时,HashSet会基于对象地址判断,而重写后则依据对象内容判断,确保了id相同的Student对象不被重复添加。
摘要由CSDN通过智能技术生成