Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to mutate values in a HashBiMap?

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?

like image 737
gvlasov Avatar asked Mar 23 '23 16:03

gvlasov


1 Answers

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.

like image 178
Jon Skeet Avatar answered Apr 02 '23 19:04

Jon Skeet