/ * Returns the entry associated with the specified key in the * HashMap. Returns null if the HashMap contains no mapping * for the key. */ final Entry<K,V> getEntry(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; }
上面是HashMap查找一个实例的过程,可以看到他的判断条件是
e.hash == hash 并且 <span style="font-family: Arial, Helvetica, sans-serif;">(k = e.key) == key || (key != null && key.equals(k))</span>
前面一个条件是说两个对象的hashCode一样,后面一个条件是说两个类相等,这里对应Object类里的两个方法:getHashCode()和equals()
因此,要想使HashMap按照我们的意思去比较两个对象一不一样,不仅要重写equals方法, 还要重写 getHashCode方法
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230640.html原文链接:https://javaforall.net
