Are mutable hashmap keys a dangerous practice?

后端 未结 7 1161
鱼传尺愫
鱼传尺愫 2020-11-22 06:58

Is it bad practice to use mutable objects as Hashmap keys? What happens when you try to retrieve a value from a Hashmap using a key that has been modified enough to change

7条回答
  •  清酒与你
    2020-11-22 07:40

    Hash maps use hash code and equality comparisons to identify a certain key-value pair with a given key. If the has map keeps the key as a reference to the mutable object, it would work in the cases where the same instance is used to retrieve the value. Consider however, the following case:

    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
    

    The above is true if the key is stored as a reference. In Java usually this is the case. In .NET for instance, if the key is a value type (always passed by value), the result will be different:

    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"
    

    Other technologies might have other different behaviors. However, almost all of them would come to a situation where the result of using mutable keys is not deterministic, which is very very bad situation in an application - a hard to debug and even harder to understand.

提交回复
热议问题