This question was initially misphrased, see the EDIT below. I'll leave it up for context.
I've been thinking about smart ways to build a bijective (i.e. one-to-one) mapping. Mapping a function A->B (many-to-one) is basically what HashMap(A,B) does. If I now wanted to have a data structure that implements something one-to-one with contains() in O(1), would there be something in the java standard libraries that I could use? Mind you, I don't need this for anything right now, this was just something I thought about recently and couldn't come up with a data structure for, so answers aren't a rush. Is there a class like that? If not, what do you think why that is?
All I could find on SO are things about hibernate, that was of no help to me.
EDIT: My question was ill phrased, so some explanation is due.
What I meant was is the "backward" mapping B->A. HashMap(A,B) has contains(A) and contains(B) both in O(1), so that's not even what I meant, sorry for the confusion. What I meant was, is there a datastructure mapping A<->B that has getValue(A) and getKey(B) in O(1)?
I realize this could be done with two HashMaps (A,B) and (B,A) that are maintained to contain the same relation, but I feel there should be one data structure that handles that without having to do it "manually".
I don't think you'll do better than two HashMaps. Writing the wrapper interface is very simple:
class OneToOneMap<Key, Value> {
public void add(Key k, Value v) {
if (!keyToVal_.contains(k) && !valToKey_.contains(v)) {
keyToVal_.add(k, v);
valToKey_.add(v, k);
}
}
private HashMap<K, V> keyToVal_;
private HashMap<V, K> valToKey_;
}
I am not sure if this is valid Java, but you get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With