Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use set of elements as key in java maps?

Tags:

java

I want to store a value based on a key, composed of set of elements. Something like the example below. Of course I know that my pseudo-example wouldn't work, as the hash of the object will probably be it's address which will be unique for each new instance, regardless of it's contents.

    // in this pseudo-example this is my SET http://algs4.cs.princeton.edu/35applications/SET.java.html
    // but the idea is that values are unique
    HashMap<SET<Integer>, String> map = new HashMap<>();
    SET a = new SET();
    a.add(1);
    a.add(2);
    a.add(5);

    SET b = new SET();
    b.add(5);
    b.add(1);
    b.add(2);

    map.put(a, "w00t");

    System.out.println(map.get(b)); // I would want to get "w00t" because my key is the same set of elements

Of course I can just sort and concatenate the SET values as a string, with a separator and use that in a HashMap<String, String> structure but that just doesn't feel right. I'm quite new to Java programming so there might be an obvious solution that I'm missing.

like image 542
ddinchev Avatar asked May 13 '15 11:05

ddinchev


1 Answers

If you use HashSet<Integer> instead of your custom SET (I'm assuming it's a custom class), it would work just fine, since HashSet overrides hashCode and equals (to be exact, HashSet extends AbstractSet which overrides these methods), so it can serve as a key in a HashMap.

However, if you modify a Set that serves as a key in your Map, you wouldn't be able to locate that key in the Map later. That's the risk you run into when using mutable objects as keys in a HashMap.

HashMap<HashSet<Integer>, String> map = new HashMap<HashSet<Integer>, String>();
HashSet<Integer> a = new HashSet<Integer>();
a.add(1);
a.add(2);
a.add(5);

HashSet<Integer> b = new HashSet<Integer>();
b.add(5);
b.add(1);
b.add(2);

map.put(a, "w00t");

System.out.println(map.get(b));

This outputs w00t.

like image 118
Eran Avatar answered Oct 11 '22 22:10

Eran