문제

In my code I'd like to have a

HashBiMap<T1, HashSet<T2>> bimap;

Is it OK to mutate values in a bimap? When I use bimap.inverse(), won't it lead to the same hashCode()-related issues it leads with a HashMap containing mutable keys?

도움이 되었습니까?

해결책

You end up with exactly the same problems as you normally get when mutating an object which is used as a key in a hash-based map, and this is easily demonstrated:

import java.util.*;
import com.google.common.collect.*;

public class Test {
    public static void main(String[] args) {
        HashBiMap<String, HashSet<String>> bimap = HashBiMap.create();
        HashSet<String> set = new HashSet<>();
        bimap.put("foo", set);
        System.out.println(bimap.inverse().get(set)); // foo
        set.add("bar");
        System.out.println(bimap.inverse().get(set)); // null 
    }
}

So no, it's not safe to do this. Ideally, you should use an immutable type as the key to completely prevent this from happening rather than relying on being careful with when you mutate the objects in question.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top