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

76
LINES

< > BotCompany Repo | #1031042 // MinimalMap - map consisting just of an unordered object array [O(n) access/put/remove]

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

Libraryless. Click here for Pure Java version (3554L/19K).

// Maximally compact implementation of such a thing
// Use SortedArrayBasedMap instead if keys are sortable
sclass MinimalMap<A, B> extends CompactAbstractMap<A, B> {
  O[] entries;
  
  *() {}
  *(Map<A, B> map) {
    if (empty(map)) ret;
    entries = new O[l(map)*2];
    int i = 0;
    for (A a, B b : map) {
      entries[i++] = a;
      entries[i++] = b;
    }
  }
  
  public int size() { ret l(entries)/2; }
  public Set<Map.Entry<A, B>> entrySet() {
    ret toLinkedHashMap().entrySet();
  }
  
  int find(O o) {
    if (entries != null)
      for (int i = 0; i < entries.length; i += 2)
        if (eq(entries[i], o))
          ret i;
    ret -1;
  }
  
  public bool containsKey(O o) {
    ret find(o) >= 0;
  }
  
  @Override
  public B get(O o) {
    int i = find(o);
    ret i >= 0 ? (B) entries[i+1] : null;
  }
  
  LinkedHashMap<A, B> toLinkedHashMap() {
    new LinkedHashMap<A, B> map;
    if (entries != null)
      for (int i = 0; i < entries.length; i += 2)
        map.put((A) entries[i], (B) entries[i+1]);
    ret map;
  }
  
  @Override
  public B put(A key, B value) {
    int i = find(key);
    
    // existing key?
    if (i >= 0) {
      B oldValue = (B) entries[i+1];
      entries[i+1] = value;
      ret oldValue;
    }
    
    // new key
    int l = l(entries);
    entries = resizeObjectArray(entries, l+2);
    entries[l] = key;
    entries[l+1] = value;
    null;
  }
  
  @Override
  public B remove(O key) {
    int i = find(key);
    if (i < 0) null;
    B oldValue = (B) entries[i+1];
    int l = l(entries);
    entries = spliceObjectArray(entries, i, l+2, null);
    ret oldValue;
  }
}

Author comment

Began life as a copy of #1030858

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1031042
Snippet name: MinimalMap - map consisting just of an unordered object array [O(n) access/put/remove]
Eternal ID of this version: #1031042/13
Text MD5: f7c46e86c95a8a8b56892e635e2e793a
Transpilation MD5: 7109e2bf87e9ac69633c54366c495066
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-07-16 06:36:30
Source code size: 1706 bytes / 76 lines
Pitched / IR pitched: No / No
Views / Downloads: 198 / 428
Version history: 12 change(s)
Referenced in: #1031058 - SortedArrayBasedMap - map based on a sorted list [O(log n) access, immutable]
#1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)