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

71
LINES

< > BotCompany Repo | #1012721 // WeakCompactHashSet - might work

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

Transpiled version (3596L) is out of date.

sclass WeakCompactHashSet<A> extends AbstractSet<A> {
  new CompactHashSet<MyWeakReference<A>> set;
  new ReferenceQueue<A> queue;
  
  sclass MyWeakReference<A> extends WeakReference<A> {
    int hash;
    
    *(A o) {
      super(o);
      hash = o.hashCode();
    }
    
    *(A o, ReferenceQueue<A> queue) {
      super(o, queue);
      hash = o.hashCode();
    }
    
    public int hashCode() { ret hash; }
    public bool equals(O o) {
      ret o instanceof MyWeakReference
        && eq(get(), ((MyWeakReference) o).get());
    }
  }
  
  // Make sure we get reaped once a minute (or whatever the policy is)
  *() {
    _registerWeakCollection(this);
  }
  
  void reap() {
    MyWeakReference ref;
    while ((ref = (MyWeakReference) queue.poll()) != null)
      set.removeIfSame(ref);
  }
  
  public int size() { reap(); ret set.size(); }
  
  public Iterator<A> iterator() {
    final Iterator<MyWeakReference<A>> it = set.iterator();
    ret iteratorFromFunction(() -> {
      while (it.hasNext()) {
        MyWeakReference<A> ref = it.next();
        A a = ref.get();
        if (a != null) ret a;
        // todo: clean up entry
      }
      null;
    });
  }
  
  public bool contains(O o) {
    reap();
    ret set.contains(new MyWeakReference(o));
  }
  
  public bool add(A a) {
    reap();
    ret set.add(new MyWeakReference(a, queue));
  }
  
  public bool remove(O o) {
    reap();
    ret set.remove(new MyWeakReference(o));
  }
  
  A find(O o) {
    reap();
    MyWeakReference<A> ref = set.find(new MyWeakReference(o));
    ret ref == null ? null : ref.get();
  }
}

Author comment

Began life as a copy of #1011596

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: #1012721
Snippet name: WeakCompactHashSet - might work
Eternal ID of this version: #1012721/18
Text MD5: df9fc8f818fe24ed08209d9194fdc8b3
Author: stefan
Category: javax / collections
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-07-11 16:11:43
Source code size: 1665 bytes / 71 lines
Pitched / IR pitched: No / No
Views / Downloads: 303 / 910
Version history: 17 change(s)
Referenced in: [show references]