1 19 24 25 package org.netbeans.core.output2; 26 27 import java.util.Arrays ; 28 29 34 final class IntList { 35 private int[] array; 36 private int used = 0; 37 private int lastAdded = Integer.MIN_VALUE; 38 39 40 IntList(int capacity) { 41 array = allocArray (capacity); 42 } 43 44 46 public synchronized void add (int value) { 47 if (value < lastAdded) { 48 throw new IllegalArgumentException ("Contents must be presorted - " + "added value " + value + " is less than preceding " + "value " + lastAdded); } 52 if (used >= array.length) { 53 growArray(); 54 } 55 array[used++] = value; 56 lastAdded = value; 57 } 58 59 private int[] allocArray (int size) { 60 int[] result = new int[size]; 61 Arrays.fill(result, Integer.MAX_VALUE); 64 return result; 65 } 66 67 public synchronized int get(int index) { 68 if (index >= used) { 69 throw new ArrayIndexOutOfBoundsException ("List contains " + used 70 + " items, but tried to fetch item " + index); 71 } 72 return array[index]; 73 } 74 75 public boolean contains (int val) { 76 return Arrays.binarySearch(array, val) >= 0; 77 } 78 79 81 public int findNearest (int val) { 82 if (size() == 0) { 83 return -1; 84 } 85 return findInRange (val, 0, size()); 86 } 87 88 89 private int findInRange (int val, int start, int end) { 90 if (end - start <= 1) { 91 return start; 92 } 93 int midPoint = start + ((end - start) / 2); 94 int valAtMidpoint = get (midPoint); 95 if (valAtMidpoint > val) { 96 return findInRange (val, start, start + ((end - start) / 2)); 97 } else { 98 return findInRange (val, start + ((end - start) / 2), end); 99 } 100 } 101 102 public int indexOf (int val) { 103 int result = Arrays.binarySearch(array, val); 104 if (result < 0) { 105 result = -1; 106 } 107 if (result >= used) { 108 result = -1; 109 } 110 return result; 111 } 112 113 114 public synchronized int size() { 115 return used; 116 } 117 118 private void growArray() { 119 int[] old = array; 120 array = allocArray(Math.round(array.length * 1.5f)); 121 System.arraycopy(old, 0, array, 0, old.length); 122 } 123 124 public String toString() { 125 StringBuffer result = new StringBuffer ("IntList ["); 126 for (int i=0; i < used; i++) { 127 result.append (i); 128 result.append (':'); 129 result.append (array[i]); 130 if (i != used-1) { 131 result.append(','); 132 } 133 } 134 result.append (']'); 135 return result.toString(); 136 } 137 138 } 139 | Popular Tags |