Is it safe to change values ​​in HashBiMap?

In my code, I would like to have

HashBiMap<T1, HashSet<T2>> bimap; 

Can I change the values ​​in the bimap? When I use bimap.inverse() , will it not lead to the same hashCode() related problems that it leads with a HashMap containing mutable keys?

+4
source share
1 answer

As a result, you get the same problems that usually arise when mutating an object that is used as a key in a map based on a hash, and this is easy to demonstrate:

 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. Ideally, you should use an immutable type as a key to completely prevent this, and not rely on being careful when you mutate the objects in question.

+6
source

Source: https://habr.com/ru/post/1498743/


All Articles