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

64
LINES

< > BotCompany Repo | #1032058 // TreeSetWithDuplicates (backup)

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

Libraryless. Click here for Pure Java version (3867L/22K).

// TreeSet variant allowing multiple elements which are considered
// equal by the comparator but not by eq().
// All operations O(log n) with n being the number of _different_ elements.
sclass TreeSetWithDuplicates<A> extends AbstractSet<A> {
  NavigableSet<Set<A>> internal;
  Comparator<A> comparator;
  int size;
  
  *() { internal = new TreeSet; }
  *(Comparator<A> *comparator) {
    internal = new TreeSet<Set<A>>((setA, setB) -> {
      ret comparator.compare(main first(setA), main first(setB));
    });
  }
  protected *(NavigableSet<Set<A>> *internal) {}
  
  // Now using CompactLinkedHashSet
  swappable Set<A> makeInternalSet() { ret new CompactLinkedHashSet; }
  
  public bool add(A a) {
    Set<A> newSet = addAndReturnCollection(makeInternalSet(), a);
    Set<A> found = navigableSet_find(internal, newSet);
    if (found != null) {
      if (!found.add(a)) false;
    } else
      internal.add(newSet);
    ++size;
    true;
  }
  
  public bool remove(O a) {
    Set<A> newSet = addAndReturnCollection(makeInternalSet(), (A) a);
    Set<A> found = navigableSet_find(internal, newSet);
    if (found == null) false;
    if (l(found) == 1)
      internal.remove(found);
    else
      found.remove(a);
    --size;
    true;
  }
  
  A first() {
    ret main first(main first(internal));
  }
  
  A last() {
    ret main last(main last(internal));
  }
  
  public ItIt<A> iterator() {
    ret nestedIterator(internal, methodLambda0 iterator);
  }
  
  public int size() { ret size; }
  
  // may return null
  Set<A> tiedForFirst() { ret main first(internal); }
  
  public bool contains(O a) {
    Set<A> newSet = addAndReturnCollection(makeInternalSet(), (A) a);
    ret navigableSet_find(internal, newSet) != null;
  }
}

Author comment

Began life as a copy of #1027809

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx

No comments. add comment

Snippet ID: #1032058
Snippet name: TreeSetWithDuplicates (backup)
Eternal ID of this version: #1032058/1
Text MD5: 02a1d6d6280d8f46bd192e16a36e9119
Transpilation MD5: 01cfada5d54f96c07ea8f29ac07f5e90
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-08-11 08:26:34
Source code size: 1804 bytes / 64 lines
Pitched / IR pitched: No / No
Views / Downloads: 131 / 180
Referenced in: [show references]