3 回答
TA贡献1799条经验 获得超9个赞
如果一个对象的hashCode()值可以根据其状态进行更改,那么我们在使用这些对象作为基于哈希的集合中的键时必须小心,以确保当它们被用作散列键时,我们不允许它们的状态更改。所有基于散列的集合假设对象的散列值在用作集合中的键时不会更改。如果键的哈希代码在集合中发生更改,则可能会出现一些不可预测和令人困惑的结果。在实践中,这通常不是一个问题-使用像List这样的可变对象作为HashMap中的键是不常见的。
TA贡献1865条经验 获得超7个赞
Object get(Object key) { int hash = key.hashCode(); //simplified, ignores hash collisions, Entry entry = getEntry(hash); if(entry != null && entry.getKey().equals(key)) { return entry.getValue(); } return null; }
Key key1 = new Key(0, 0); map.put(key1, value1); key1.setA(5); Key key2 = new Key(0, 0); map.get(key2);
if(entry != null && entry.getKey().equals(key))
TA贡献1856条经验 获得超5个赞
T keyOne = ...; T keyTwo = ...; // At this point keyOne and keyTwo are different instances and // keyOne.equals(keyTwo) is true. HashMap myMap = new HashMap(); myMap.push(keyOne, "Hello"); String s1 = (String) myMap.get(keyOne); // s1 is "Hello" String s2 = (String) myMap.get(keyTwo); // s2 is "Hello" // because keyOne equals keyTwo mutate(keyOne); s1 = myMap.get(keyOne); // returns "Hello" s2 = myMap.get(keyTwo); // not found
T keyOne = ...; T keyTwo = ...; // At this point keyOne and keyTwo are different instances // and keyOne.equals(keyTwo) is true. Dictionary myMap = new Dictionary(); myMap.Add(keyOne, "Hello"); String s1 = (String) myMap[keyOne]; // s1 is "Hello" String s2 = (String) myMap[keyTwo]; // s2 is "Hello" // because keyOne equals keyTwo mutate(keyOne); s1 = myMap[keyOne]; // not found s2 = myMap[keyTwo]; // returns "Hello"
- 3 回答
- 0 关注
- 438 浏览
相关问题推荐
添加回答
举报