Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

60
LINES

< > BotCompany Repo | #1035059 // BijectiveMap - enforced bijective map (including fast backward lookup)

JavaX fragment (include) [tags: use-pretranspiled]

Transpiled version (8286L) is out of date.

1  
// no null keys or null values
2  
sclass BijectiveMap<A, B> extends CompactAbstractMap<A, B> {
3  
  new Map<A, B> forward;
4  
  new Map<B, A> backward;
5  
  
6  
  *() {}
7  
  *(bool ordered) {
8  
    if (ordered) {
9  
      forward = new LinkedHashMap;
10  
      backward = new LinkedHashMap;
11  
    }
12  
  }
13  
  
14  
  @Override public B put(A a, B b) {
15  
    assertNotNull(a);
16  
    assertNotNull(b);
17  
    A oldKey = backward.get(b);
18  
    if (eq(oldKey, a))
19  
      ret b; // nothing to do
20  
      
21  
    // remove old mapping of b
22  
    if (oldKey != null)
23  
      forward.remove(oldKey);
24  
      
25  
    // remove old mapping of a
26  
    B oldValue = forward.get(a);
27  
    if (oldValue != null)
28  
      backward.remove(b);
29  
      
30  
    // add/overwrite new mapping
31  
    backward.put(b, a);
32  
    ret forward.put(a, b);
33  
  }
34  
  
35  
  @Override public B remove(O a) {
36  
    B b = forward.get(a);
37  
    if (b != null) {
38  
      forward.remove(a);
39  
      backward.remove(b);
40  
    }
41  
    ret b;
42  
  }
43  
  
44  
  @Override public B get(O a) {
45  
    ret forward.get(a);
46  
  }
47  
  
48  
  A inverseGet(B b) {
49  
    ret backward.get(b);
50  
  }
51  
  
52  
  public Set<A> keySet() { ret immutableSet(forward.keySet()); }
53  
  public Set<B> valueSet() { ret immutableSet(backward.keySet()); }
54  
  public Set<Map.Entry<A, B>> entrySet() { ret immutableSet(forward.entrySet()); }
55  
  
56  
  public int size() { ret forward.size(); }
57  
  
58  
  Map<A, B> forwardMap() { ret immutableMap(forward); }
59  
  Map<B, A> backwardMap() { ret immutableMap(backward); }
60  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035059
Snippet name: BijectiveMap - enforced bijective map (including fast backward lookup)
Eternal ID of this version: #1035059/14
Text MD5: f363f1141ab96248aee09eaa3d6bd97c
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-05-06 20:20:18
Source code size: 1471 bytes / 60 lines
Pitched / IR pitched: No / No
Views / Downloads: 175 / 293
Version history: 13 change(s)
Referenced in: [show references]