今天看到這樣一個問題:java
/**補充完該類,不修改main方法,使得get()方法能夠取到值*/
算法
package test; import java.util.HashMap; import java.util.Map; public class StudentTest { private static final class Student { private static String name; public Student(String name) { this.name = name; } } public static void main(String[] args) { Map p = new HashMap(); p.put(new Student("lily"), "sister"); System.out.println(p.get("lily")); System.out.print(p.keySet().iterator().next()); } }
來源: <http://xtwxgh.iteye.com/blog/78459>測試
測試發現重寫student的hashcode也不能重現,本覺得hashmap只經過hash後的index做爲尋找value的策略,結果仍是不行 this
看源碼get方法發現下面,
spa
static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; /** * Creates new entry. */ Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; }
key除了經過hash比較,還要比較自己key和查詢key,下面的代碼展現Entry除了要記錄hash還要記錄hash時的Key(object類型)code
final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); 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 && ))) return e; } return null; }
總結:對象
對於hashcode,通常是不推薦重寫的,而hashcode自己也是爲了對於hashmap這類須要使用hash算法的對象而產生的,若是非要按照本身的需求去實現key,value映射,必需要修改Hashmap中的get等方法,單純修改key的hashcode算法是不夠blog