HashSet实现自定义类的add()方法的原理

HashSet实现自定义类的add()方法的原理

自定义一个类

public class Student {
	private String id;
	public Student(String id) {
		this.id = id;
	}

}

测试类

public static class Test{
        HashSet<Student> set = new HashSet<Student>();
		set.add(new Student("111"));
		set.add(new Student("111"));
		System.out.println(new Student("111").hashCode());
		System.out.println(new Student("111").hashCode());
}

add方法

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

put方法

 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

putVal方法

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;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

测试类代码运行之后,两个学生对象调用父类Object的方法(两个学生对象的地址不同,所以hash值也不同)都存了进去,但是set中不能放重复的值,所以我们要重写父类Object的hashCode方法,使ID相同的两个学生对象不能重复放进去set集合中。

重写hashCode方法(在Student类中重写)

@Override
	public int hashCode() {
		return id.hashCode();
	}

重写了hashCode方法之后,取Student类中对象hash值调用Student类中重写过的hashCode方法,重写后的方法返回字符串id的hash值,调用String类下的hashCode方法。

代码分析:

  if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

添加第二个对象时,进入第一个if语句块,table存有值,不为null,数组长度n也不为0,执行下一个if语句块

   if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

因为相同字符串的hash值相同,所以tab[i = = (n - 1) & hash] 赋值给p,p不为null,执行else语句块

第一次存入的对象的ID和第二次存入的ID相同,又重写了hashCode方法,所以第一次的hash值和第二次相同,但是两者的地址不相同,key存的是第二次的地址,不为null,由于没有重写equals,所以比较的是地址,p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))) 是false,p不是TreeNode类,进入下面的else语句块,这里面是一个死循环,寻找一个为null的空间,将第二个对象保存了,结束循环,e指向了第一次的地址,e为null,返回null,add方法返回false,保存成功。所以要重写equals方法,让e不为null,保存失败。

重写equals方法

@Override
public boolean equals(Object obj) {
	if (obj instanceof Student) {
		Student student = (Student) obj;
		return this.id.equals(student.id);
		}
		return false;
	}

重写equals方法之后

第一次存入的对象的ID和第二次存入的ID相同,又重写了hashCode方法,所以第一次的hash值和第二次相同,但是两者的地址不相同,key存的是第二次的地址,key显然不为null,由于重写了equals,改为比较的Student类对象的id值,所以key.equals(k)为true,所以该if的条件成立。e指向了第一次存储的位置,所以不为null,返回oldValue,存储失败。

posted @ 2021-05-12 21:48  imetal  阅读(128)  评论(0)    收藏  举报