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.

// no null keys or null values
sclass BijectiveMap<A, B> extends CompactAbstractMap<A, B> {
  new Map<A, B> forward;
  new Map<B, A> backward;
  
  *() {}
  *(bool ordered) {
    if (ordered) {
      forward = new LinkedHashMap;
      backward = new LinkedHashMap;
    }
  }
  
  @Override public B put(A a, B b) {
    assertNotNull(a);
    assertNotNull(b);
    A oldKey = backward.get(b);
    if (eq(oldKey, a))
      ret b; // nothing to do
      
    // remove old mapping of b
    if (oldKey != null)
      forward.remove(oldKey);
      
    // remove old mapping of a
    B oldValue = forward.get(a);
    if (oldValue != null)
      backward.remove(b);
      
    // add/overwrite new mapping
    backward.put(b, a);
    ret forward.put(a, b);
  }
  
  @Override public B remove(O a) {
    B b = forward.get(a);
    if (b != null) {
      forward.remove(a);
      backward.remove(b);
    }
    ret b;
  }
  
  @Override public B get(O a) {
    ret forward.get(a);
  }
  
  A inverseGet(B b) {
    ret backward.get(b);
  }
  
  public Set<A> keySet() { ret immutableSet(forward.keySet()); }
  public Set<B> valueSet() { ret immutableSet(backward.keySet()); }
  public Set<Map.Entry<A, B>> entrySet() { ret immutableSet(forward.entrySet()); }
  
  public int size() { ret forward.size(); }
  
  Map<A, B> forwardMap() { ret immutableMap(forward); }
  Map<B, A> backwardMap() { ret immutableMap(backward); }
}

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: 174 / 292
Version history: 13 change(s)
Referenced in: #1003674 - Standard Classes + Interfaces (LIVE continued in #1034167)
#1035371 - BijectiveMap - duplicate before implementing Map interface