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

43
LINES

< > BotCompany Repo | #1035371 // BijectiveMap - duplicate before implementing Map interface

JavaX fragment (include)

1  
// no null keys or null values
2  
sclass BijectiveMap<A, B> {
3  
  new Map<A, B> forward;
4  
  new Map<B, A> backward;
5  
  
6  
  void put(A a, B b) {
7  
    assertNotNull(a);
8  
    assertNotNull(b);
9  
    A oldKey = backward.get(b);
10  
    if (eq(oldKey, a))
11  
      ret; // nothing to do
12  
    if (oldKey != null)
13  
      forward.remove(oldKey); // remove old mapping
14  
      
15  
    // add/overwrite new mapping
16  
    forward.put(a, b);
17  
    backward.put(b, a);
18  
  }
19  
  
20  
  void remove(A a) {
21  
    B b = forward.get(a);
22  
    if (b == null)
23  
      ret; // nothing to do
24  
    forward.remove(a);
25  
    backward.remove(b);
26  
  }
27  
  
28  
  B get(A a) {
29  
    ret forward.get(a);
30  
  }
31  
  
32  
  A inverseGet(B b) {
33  
    ret backward.get(b);
34  
  }
35  
  
36  
  Set<A> keySet() { ret immutableSet(forward.keySet()); }
37  
  Set<B> valueSet() { ret immutableSet(backward.keySet()); }
38  
  
39  
  int size() { ret forward.size(); }
40  
  
41  
  Map<A, B> forwardMap() { ret immutableMap(forward); }
42  
  Map<B, A> backwardMap() { ret immutableMap(backward); }
43  
}

Author comment

Began life as a copy of #1035059

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035371
Snippet name: BijectiveMap - duplicate before implementing Map interface
Eternal ID of this version: #1035371/1
Text MD5: fd50962b6163b3229d5f91fa4ad39bbd
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-05-03 12:36:40
Source code size: 1000 bytes / 43 lines
Pitched / IR pitched: No / No
Views / Downloads: 96 / 110
Referenced in: [show references]