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

69
LINES

< > BotCompany Repo | #1028525 // ChunkedIntList - stored in fixed-size chunks

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

Libraryless. Click here for Pure Java version (2816L/18K).

final sclass ChunkedIntList extends RandomAccessAbstractList<Int> {
  int chunkShift = 16; // => chunkSize = 65536
  new ArrayList<int[]> chunks;
  int actualChunks; // roughly keep track of chunk list's internal capacity so we can shrink in time
  int size;
  
  public void add(int i) {
    ensureCapacity(size+1);
    set(size, i);
    ++size;
  }
  
  public Int set(int i, Int value) {
    ret set(i, (int) value);
  }
  
  public int set(int i, int value) {
    int[] chunk = chunks.get(i >> chunkShift);
    int idx = i & (chunkSize()-1);
    int old = chunk[idx];
    chunk[idx] = value;
    ret old;
  }
  
  public bool add(Int i) {
    add((int) i);
    true;
  }
  
  public int size() { ret size; }
  
  public Int get(int i) {
    ret getPrimitive(i);
  }
  
  public int getPrimitive(int i) {
    if (i >= 0 && i < size) ret chunks.get(i >> chunkShift)[i & (chunkSize()-1)];
    throw new IndexOutOfBoundsException(i + "/" + size);
  }
  
  void ensureCapacity(int minCapacity) {
    while (l(chunks) << chunkShift < minCapacity) {
      chunks.add(new int[chunkSize()]);
      actualChunks = max(actualChunks, l(chunks));
    }
  }
  
  int[] toIntArray() {
    int[] a = new int[size];
    int i = 0;
    for (int[] chunk : chunks) {
      System.arraycopy(chunk, 0, a, i, min(chunk.length, size-i));
      i += chunk.length;
    }
    ret a;
  }
  
  int chunkSize() { ret 1 << chunkShift; }
  
  void truncateAt(int idx) {
    size = idx;
    while (size <= (l(chunks)-1) << chunkShift)
      popLast(chunks);
    if (l(chunks)*2 < actualChunks) {
      chunks.trimToSize();
      actualChunks = l(chunks);
    }
  }
}

Author comment

Began life as a copy of #1012238

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: #1028525
Snippet name: ChunkedIntList - stored in fixed-size chunks
Eternal ID of this version: #1028525/9
Text MD5: 309d949f1ffd6a6e6a3b04bd3cbcb191
Transpilation MD5: 29a46e930c5a95ae5633faaa9cbbdbae
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-26 13:49:57
Source code size: 1705 bytes / 69 lines
Pitched / IR pitched: No / No
Views / Downloads: 249 / 582
Version history: 8 change(s)
Referenced in: #1029225 - ChunkedLongList - stored in fixed-size chunks
#1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)