1

Looking for a away to link two variables. sort of like a hashmap but where the key acts as a value and a key. for example, i want to keep track of two people having a conversation.

    int recipient1ID = 1111;
    int recipient2ID = 2222; 

    LinkedVar<Integer, Integer> conversation = new LinkedVar<Integer, Integer>();

    conversation.put(recipient1ID, recipient2ID);// add link

    conversation.get(recipient1ID);// returns recipient2ID
    conversation.get(recipient2ID);// returns recipient1ID

i want to call one variable and it return the other. i hope this makes sense. Thanks

Ryan Maddox
  • 312
  • 1
  • 5
  • 15
  • 1
    Sounds like you want a bimap... e.g. https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/BiMap.java – Jon Skeet Nov 26 '14 at 13:37

2 Answers2

2

Have a look at Guava's BiMap - it's a bidirectional map that may fill your needs. The api looks a bit different though.

David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125
1

What you want can be implemented using two Maps, one for each relation direction.

Map<Integer, Integer> caller2recipient = ...;
Map<Integer, Integer> recipient2caller = ...;

Aggregating these two maps you could implement your LinkedVar class as:

public class LinkedVar<T> {

    public LinkedVar() {
        fromto = new HashMap<T,T>();
        tofrom = new HashMap<T,T>();
    }

    public boolean put(T a, T b)
    {
        if(fromto.containsKey(a) || tofrom.containsKey(b))
            return false;
        fromto.put(a, b);
        tofrom.put(b, a);
        return true;
    }

    public T get(T key)   
    {
        for(Map<T,T> m: Arrays.asList(fromto, tofrom))
            if(m.containsKey(key)) return m.get(key);
        return null;
    }

    private Map<T,T> fromto;
    private Map<T,T> tofrom;

}

Below, this class used in your example:

    int recipient1ID = 1111;
    int recipient2ID = 2222; 

    LinkedVar<Integer> conversation = new LinkedVar<>();
    conversation.put(recipient1ID, recipient2ID);// add link

    System.out.println(conversation.get(recipient1ID));// returns recipient2ID
    System.out.println(conversation.get(recipient2ID));// returns recipient1ID

Note that, as BiMap class from Guava library does, LinkedVar could be parametrized with two types (one for the key and one for the value) but that implies get has to be splitted into two methods with different method identifiers:

  • get
  • getReverse

If they were identified by the same name:

public S get(T key)   
{
    if(fromto.containsKey(key)) return fromto.get(key);
    return null;
}


public T get(S key)   
{
    if(tofrom.containsKey(key)) return tofrom.get(key);
    return null;
}    

Java could not distinguish both methods for those cases where T and S are the same type. In fact, Java's compiler (in contrast to G++) won't allow to deffine that template.