62,635
社区成员




public static void hashmap()
throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
HashMap<String, String> map = new HashMap<>();
map.put("1234", "1234");
map.put("2345", "2345");
Field table = map.getClass().getDeclaredField("table");
table.setAccessible(true);
Object value = table.get(map);
Class c2 = Class.forName("java.util.HashMap$Entry");
for(int i = 0; i < Array.getLength(value); i ++) {
Object v = Array.get(value, i);
if(v != null) {
Entry<String, String> c = (Entry<String, String>) v;
Field next = c2.getDeclaredField("next");
next.setAccessible(true);
// Object n = next.get(v);
for(; c != null; c = (Entry<String, String>)next.get(c)) {
System.out.println(c.getKey());
System.out.println(c.getValue());
}
}
}
}
HashMap<String, String> h = new HashMap<>();
h.put("1", "ok");
h.put("2", "No");
//当我们put相同key的时候,会把最新的值放在那个List的第一个,我用什么方式可以get到这个List或者tree呢?
Set<String> keySet = h.keySet();//这个就是楼主要的list或tree
for(String s:keySet){
System.out.println(s+"=="+h.get(s));
}
//如果不是 那么你所表达的无人能解了
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
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;
}
如果 key 是同一个对象,或者 equals (默认也是同一个对象为 true) 一致的话,才会覆盖。
但是是纯粹的指针性质的覆盖,没有看到楼主所说的放进一个 LinkedList (current 的是最新的、next 指向覆盖过的历史) 的逻辑。
断点跟踪查看 HashMap 对象的内部结构值,也只看到了哈希值相同时的 LinkedList,没有找到楼主所说的装载覆盖历史的 LinkedList。
以上红色部分,向楼主请教一下,能否解释一下?