1 package gov.nasa.jpf.util; 20 21 37 public class DynamicIntArray { 38 final static int DEFAULT_CHUNKSIZE = 256; 39 final static int INIT_CHUNKS = 16; 40 41 int chunkSize; 42 int[][] data; 43 int length; 44 45 public DynamicIntArray () { 46 this( DEFAULT_CHUNKSIZE); 47 } 48 49 public DynamicIntArray (int chunkSize) { 50 this.chunkSize = chunkSize; 51 52 data = new int[INIT_CHUNKS][]; 53 } 54 55 public boolean isEmpty () { 56 return (length == 0); 57 } 58 59 62 public void grow(int index) { 63 if (index >= length) { 64 int i = index / chunkSize; 65 int j = index % chunkSize; 66 67 if (i >= data.length) { 68 int new_size = (i * 3) / 2 + 1; 70 int[][] newChunk = new int[new_size][]; 71 System.arraycopy(data, 0, newChunk, 0, data.length); 72 data = newChunk; 73 } 74 length = index + 1; 75 } 76 } 77 78 public int get (int index) { 79 if (index >= length) { 80 throw new IndexOutOfBoundsException ("Index " + index + 81 " is outside of 0.." + 82 (length - 1)); 83 } 84 int i = index / chunkSize; 85 int j = index % chunkSize; 86 87 if (data[i] == null) { 88 return 0; 89 } else { 90 return data[i][j]; 91 } 92 } 93 94 public void set (int index, int value) { 95 int i = index / chunkSize; 96 int j = index % chunkSize; 97 98 grow(index); 99 if (data[i] == null) { 101 data[i] = new int[chunkSize]; 102 } 103 data[i][j] = value; 104 } 105 106 public int size() { 107 return length; 108 } 109 110 public String toString() { 111 int i; 112 StringBuffer sb = new StringBuffer (length*4); 113 114 sb.append('{'); 115 int l = length-1; 116 for (i=0; i<l; i++) { 117 sb.append(get(i)); 118 sb.append(','); 119 } 120 sb.append(get(i)); 121 sb.append('}'); 122 123 return sb.toString(); 124 } 125 126 public int[] toArray (int[] buf) { 127 if (buf.length < length) { 128 buf = new int[length]; 129 } 130 for (int i=0; i<length; i++) { 131 buf[i] = get(i); 132 } 133 134 return buf; 135 } 136 137 171 } 172 173 | Popular Tags |