ddinchev
ddinchev

Reputation: 34673

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

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.

Upvotes: 9

Views: 2395

Answers (4)

user4895454
user4895454

Reputation: 1

You didn't add set b to your map. First add both sets and then try to get value associated with the key b.

Upvotes: -3

SanyaLuc
SanyaLuc

Reputation: 116

It depends on you of SET class implementation. You can either extend java.util.HashSet class or implement equals() and hashCode() methods in your SET class. Any solution will work.

Upvotes: -1

Eran
Eran

Reputation: 393936

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.

Upvotes: 9

ASA
ASA

Reputation: 1971

Create a collection class and override hashcode() in a way where the same hashcode is returned for different collection instances with the same content. You can simply override the method in a class deriving from your desired collection. You do have to reimplement equals(Object o) as well.

Upvotes: 0

Related Questions