1 22 23 package com.sosnoski.util; 24 25 import java.lang.reflect.Array ; 26 27 39 40 public abstract class GrowableBase 41 { 42 43 public static final int DEFAULT_SIZE = 8; 44 45 46 protected int m_countLimit; 47 48 49 protected int m_maximumGrowth; 50 51 58 59 public GrowableBase(int size, int growth, Class type) { 60 Object array = Array.newInstance(type, size); 61 m_countLimit = size; 62 m_maximumGrowth = growth; 63 setArray(array); 64 } 65 66 72 73 public GrowableBase(int size, Class type) { 74 this(size, Integer.MAX_VALUE, type); 75 } 76 77 82 83 public GrowableBase(GrowableBase base) { 84 this(base.m_countLimit, base.m_maximumGrowth, 85 base.getArray().getClass().getComponentType()); 86 } 87 88 95 96 protected abstract Object getArray(); 97 98 105 106 protected abstract void setArray(Object array); 107 108 117 118 protected void resizeCopy(Object base, Object grown) { 119 System.arraycopy(base, 0, grown, 0, Array.getLength(base)); 120 } 121 122 130 131 protected void discardValues(int from, int to) { 132 Object values = getArray(); 133 if (!values.getClass().getComponentType().isPrimitive()) { 134 Object [] objects = (Object [])values; 135 for (int i = from; i < to; i++) { 136 objects[i] = null; 137 } 138 } 139 } 140 141 152 153 protected void growArray(int required) { 154 Object base = getArray(); 155 int size = Math.max(required, 156 m_countLimit + Math.min(m_countLimit, m_maximumGrowth)); 157 Class type = base.getClass().getComponentType(); 158 Object grown = Array.newInstance(type, size); 159 resizeCopy(base, grown); 160 m_countLimit = size; 161 setArray(grown); 162 } 163 164 170 171 public final void ensureCapacity(int min) { 172 if (min > m_countLimit) { 173 growArray(min); 174 } 175 } 176 177 186 187 protected Object buildArray(Class type, int offset, int length) { 188 Object copy = Array.newInstance(type, length); 189 System.arraycopy(getArray(), offset, copy, 0, length); 190 return copy; 191 } 192 } 193 | Popular Tags |