なぜHashMapでkeyが可変オブジェクトである必要があるのか
2862 ワード
HashMapではkeyが可変オブジェクトである必要があることを提唱していますが、実際にはHashMapのkeyを無理に可変オブジェクトにすることもできますが、これは多くの潜在的な危険をもたらします.
なぜならkeyのhashCodeが変わったからです.
これはArrayListのhashCodeメソッドです.
要素を増やすとhashCodeも変化し,これにより元のkeyに対応するvalueが見つからなくなる.
HashMap<List<String>, Object> changeMap = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
Object objectValue = new Object();
changeMap.put(list, objectValue);
System.out.println(changeMap.get(list));
list.add("hello world");
System.out.println(changeMap.get(list));
/*
:
java.lang.Object@74a14482
null
*/
なぜならkeyのhashCodeが変わったからです.
これはArrayListのhashCodeメソッドです.
/**
* Returns the hash code value for this list.
*
* This implementation uses exactly the code that is used to define the
* list hash function in the documentation for the {@link List#hashCode}
* method.
*
* @return the hash code value for this list
*/
public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}
要素を増やすとhashCodeも変化し,これにより元のkeyに対応するvalueが見つからなくなる.