What you want can be implemented using two Map
s, 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:
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.