java的hashcode和equals

在java中,equals和hashcode是有设计要求的,equals相等,则hashcode一定相等,反之则不然。
为何会有这样的要求?
在集合中,比如HashSet中,要求放入的对象不能重复,怎么判定呢?
首先会调用hashcode,如果hashcode相等,则继续调用equals,也相等,则认为重复。
如果重写equals后,如果不重写hashcode,则hashcode就是继承自Object的,返回内存编码,这时候可能出现equals相等,而hashcode不等,你的对象使用集合时,就会等不到正确的结果


public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
原文地址:https://www.cnblogs.com/xiaoqisfzh/p/5792970.html