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

63
LINES

< > BotCompany Repo | #1031784 // SmallArrayBasedMap - map based on an array in any order [slow! O(n) access. Use ony for small maps. immutable]

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

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

// you can arrange the entries in a self-chosen order
// so it's like a very compact LinkedHashMap
// Only good for very small maps
sclass SmallArrayBasedMap<A, B> extends CompactAbstractMap<A, B> {
  O[] entries; // key, value, ... (any order of entries)
  
  *() {}
  *(Map<A, B> map) {
    int n = l(map);
    if (n == 0) ret;
    entries = new O[n*2];
    int i = 0;
    fOr (A key, B value : map) {
      entries[i++] = key;
      entries[i++] = value;
    }
  }
  
  public int size() { ret l(entries)/2; }
  public Set<Map.Entry<A, B>> entrySet() {
    ret new AbstractSet<Map.Entry<A, B>>() {
      public int size() { ret SmallArrayBasedMap.this.size(); }
      
      public Iterator<Map.Entry<A, B>> iterator() {
        ret new Iterator<Map.Entry<A, B>>() {
          int idx;
          
          public bool hasNext() {
            ret idx < l(entries);
          }
          
          public Map.Entry<A, B> next() {
            SimpleEntry<A, B> e = new SimpleEntry<A, B>((A) entries[idx], (B) entries[idx+1]);
            idx += 2;
            ret e;
          }
        };
      }
    };
  }
  
  // returns actual index in entries array
  int find(O key) {
    int n = l(entries);
    //if (n == 0) ret -1;
    //int hash = _hashCode(key);
    for (int i = 0; i < n; i += 2)
      //if (_hashCode(entries[i]) == hash
      if (eq(key, entries[i]))
        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;
  }
}

Author comment

Began life as a copy of #1031058

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1031784
Snippet name: SmallArrayBasedMap - map based on an array in any order [slow! O(n) access. Use ony for small maps. immutable]
Eternal ID of this version: #1031784/1
Text MD5: 51e1dfec40d32a1b6f94124d30fcf519
Transpilation MD5: d182fa19d47e5825428b326c8f5caf01
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-06-29 18:43:22
Source code size: 1630 bytes / 63 lines
Pitched / IR pitched: No / No
Views / Downloads: 257 / 404
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)