Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with two Key for a value?

I want to create a map that has two key :

map.put (key1,key2,value1);// Insert into map
map.get(key1,key2); // return value1

i have looking into multikeyMap but i don't know how i will do it

like image 567
Wassim Sboui Avatar asked May 28 '12 16:05

Wassim Sboui


2 Answers

Sounds like you just want a key which is created from two values. You may well find that those two values should naturally be encapsulated into another type anyway - or you could create a Key2<K1, K2> type. (The naming here would allow for Key3, Key4 etc. I wouldn't encourage you to go too far though.)

For something in between, you could create a private static class within the class where this is really needed (if it's only an internal implementation detail). If it's not a natural encapsulation (e.g. it's something like "name and population", which doesn't make sense outside this specific scenario) then it would be good in terms of keeping meaningful property names, but without exposing it publicly.

In any of these scenarios, you'll end up with a new type with two final variables which are initialized in the constructor, and which contribute to both equals and hashCode. For example:

public final class Key2<K1, K2> {
    private final K1 part1;
    private final K2 part2;

    public Key2(K1 part1, K2 part2) {
        this.part1 = part1;
        this.part2 = part2;
    }

    @Override public boolean equals(Object other) {
        if (!(other instanceof Key2)) {
            return false;
        }
        // Can't find out the type arguments, unfortunately
        Key2 rawOther = (Key2) other;
        // TODO: Handle nullity
        return part1.equals(rawOther.part1) &&
            part2.equals(rawOther.part2);
    }

    @Override public int hashCode() {
        // TODO: Handle nullity
        int hash = 23;
        hash = hash * 31 + part1.hashCode();
        hash = hash * 31 + part2.hashCode();
        return hash;
    }

    // TODO: Consider overriding toString and providing accessors.
}

The more situation-specific types would be slightly simpler as they wouldn't be generic - in particular this would mean you wouldn't need to worry about the type arguments, and you could give the variables better names.

like image 106
Jon Skeet Avatar answered Sep 19 '22 09:09

Jon Skeet


How about

class Key{
 private final String key1;
 private final String key2;
//accessors + hashcode + equals()
}

and

Map<Key, Value> map
like image 41
jmj Avatar answered Sep 21 '22 09:09

jmj