Last active
January 13, 2018 07:13
-
-
Save kamathln/0a03cc981c6aa8bc07695817eea3e6ec to your computer and use it in GitHub Desktop.
One to One Mapping in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* Created by [email protected] on 9/1/18. | |
* | |
* Preliminary idea .. not all Map related stuff are implemented. | |
* Tested with a Long and Integer. | |
* | |
* if new value value is set for a key, in addition to updating key->value mapping, | |
* the old value -> key mapping is removed and new value-> key is added. Same goes for | |
* updating key vor a value. | |
* | |
* As the behaviour is same on both sides, instead of claling them key and value, | |
* we call them A and B | |
* | |
*/ | |
public class OneToOneMap<Type1, Type2> { | |
private Map<Type1, Type2> map_a2b; | |
private Map<Type2, Type1> map_b2a; | |
public OneToOneMap() { | |
map_a2b = new HashMap<>(); | |
map_b2a = new HashMap<>(); | |
} | |
public Type2 getFromA(Type1 key) { | |
return map_a2b.get(key); | |
} | |
public Type1 getFromB(Type2 key) { | |
return map_b2a.get(key); | |
} | |
public void putInA(Type1 key, Type2 value) { | |
if (map_a2b.containsKey(key)) { | |
map_b2a.remove(map_a2b.get(key)); | |
} | |
map_a2b.put(key, value); | |
map_b2a.put(value, key); | |
} | |
public void putInB(Type2 key, Type1 value) { | |
if (map_b2a.containsKey(key)) { | |
map_a2b.remove(map_b2a.get(key)); | |
} | |
map_b2a.put(key, value); | |
map_a2b.put(value, key); | |
} | |
public boolean aContains(Type1 key){ | |
return map_a2b.containsKey(key); | |
} | |
public boolean bContains(Type2 key){ | |
return map_b2a.containsKey(key); | |
} | |
public void removeFromA(Type1 key){ | |
map_b2a.remove(map_a2b.get(key)); | |
map_a2b.remove(key); | |
} | |
public void removeFromB(Type2 key){ | |
map_a2b.remove(map_b2a.get(key)); | |
map_b2a.remove(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment