1 8 12 package jfun.util; 13 14 20 public final class IntArray { 21 private int[] buf; 22 private int len = 0; 23 27 public int[] toArray(){ 28 final int[] ret = new int[len]; 29 for(int i=0; i<len; i++){ 30 ret[i] = buf[i]; 31 } 32 return ret; 33 } 34 38 public IntArray(int capacity){ 39 this.buf = new int[capacity]; 40 } 41 44 public IntArray(){ 45 this(10); 46 } 47 50 public int size(){ 51 return len; 52 } 53 private void checkIndex(int i){ 54 if(i<0 || i>=len) 55 throw new ArrayIndexOutOfBoundsException (i); 56 } 57 63 public int get(int i){ 64 checkIndex(i); 65 return buf[i]; 66 } 67 74 public int set(int i, int val){ 75 checkIndex(i); 76 final int old = buf[i]; 77 buf[i] = val; 78 return old; 79 } 80 private static int calcSize(int l, int factor){ 81 final int rem = l%factor; 82 return l/factor*factor + (rem>0?factor:0); 83 } 84 88 public void ensureCapacity(int capacity){ 89 if(capacity > buf.length){ 90 final int factor = buf.length / 2 + 1; 91 grow(calcSize(capacity-buf.length, factor)); 92 } 93 } 94 private void grow(int l){ 95 final int[] nbuf = new int[buf.length+l]; 96 for(int i=0; i<buf.length; i++){ 97 nbuf[i] = buf[i]; 98 } 99 buf = nbuf; 100 } 101 106 public IntArray add(int i){ 107 ensureCapacity(len+1); 108 buf[len++] = i; 109 return this; 110 } 111 } 112 | Popular Tags |