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

23
LINES

< > BotCompany Repo | #1029154 // SimpleStack - shrinks array when shrunk logically. Note: only made for adding and removing from the end, other operations may be slow

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

Libraryless. Click here for Pure Java version (59L/1K).

final sclass SimpleStack<A> extends RandomAccessAbstractList<A> {
  new ArrayList<A> l;
  int peak;
  
  public A get(int i) { ret l.get(i); }
  public int size() { ret l.size(); }

  public A set(int i, A a) { ret l.set(i, a); }
  public void add(int i, A a) { l.add(i, a); checkSize(); }
  public A remove(int i) { A a = l.remove(i); checkSize(); ret a; }
  
  void checkSize {
    int n = size();
    if (n > peak) peak = n; // record new peak size (~actual capacity)
    if (n*2 < peak) { // shrink physically when below half of peak
      ifdef SimpleStack_debug
        print("Shrinking SimpleStack: " + peak + " => " + n);
      endifdef
      trimToSize(l);
      peak = n;
    }
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1029154
Snippet name: SimpleStack - shrinks array when shrunk logically. Note: only made for adding and removing from the end, other operations may be slow
Eternal ID of this version: #1029154/4
Text MD5: 8720ecaec9d09aab7724a0a1cf536334
Transpilation MD5: a1709c2825b789261ce944dfb4ea37bc
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-26 03:11:04
Source code size: 715 bytes / 23 lines
Pitched / IR pitched: No / No
Views / Downloads: 220 / 516
Version history: 3 change(s)
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)