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

58
LINES

< > BotCompany Repo | #1011691 // Test WeakHashMap2 (OK)

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (1898L/13K).

!7

unset flag SymbolAsString.

sclass Symbol {
  S text;
  
  *() {}
  *(S *text, bool dummy) {} // weird signature to prevent accidental calling
  
  public int hashCode() { ret main.hashCode(text); }
  toString { ret text; }
  public bool equals(O o) {
    ret this == o;
  }
}

sclass SymbolTester {
  S text;
  
  *() {}
  *(S *text) {}
  
  public int hashCode() { ret main.hashCode(text); }
  public bool equals(O o) {
    ret o instanceof Symbol && eq(text, o/Symbol.text);
  }
}

static new WeakHashMap2<Symbol, Bool> symbolMap;

static Symbol symbol(S s) {
  if (s == null) null;
  synchronized(symbolMap) {
    // This is a trick that works because of how WeakHashMap compares keys.
    SymbolTester test = new(s);
    WeakHashMap2.Entry<Symbol, Bool> e = symbolMap.getEntry(test);
    Symbol sym = e == null ? null : (Symbol) e.get();
    //O e = call(symbolMap, 'getEntry, test);
    //Symbol sym = e == null ? null : ((WeakReference<Symbol>) e).get();
    if (sym == null)
      symbolMap.put(sym = Symbol(s, false), Bool.TRUE);
    ret sym;
  }
}

p {
  S s1 = "a", s2 = lower("A");
  assertNotIdentical(s1, s2); // Now more clearly showing the improvement
  Symbol a = symbol(s1);
  Symbol a2 = symbol(s2);
  assertEquals("a", str(a));
  assertEquals("a", str(a2));
  assertIdentical(a, a2);
  Symbol b = symbol("b");
  assertEquals("b", str(b));
  print("OK");
}

Author comment

Began life as a copy of #1010607

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1011691
Snippet name: Test WeakHashMap2 (OK)
Eternal ID of this version: #1011691/7
Text MD5: 09005e451e7295d9cbcd6f68f8719a12
Transpilation MD5: 1c4e03eeebe5d517080c1a99f12a5095
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-12-10 05:32:50
Source code size: 1436 bytes / 58 lines
Pitched / IR pitched: No / No
Views / Downloads: 553 / 1220
Version history: 6 change(s)
Referenced in: #1011693 - Test internPerProgram (OK)