1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.util; 18 19 import com.android.internal.util.ArrayUtils; 20 21 /** 22 * SparseArrays map integers to Objects. Unlike a normal array of Objects, 23 * there can be gaps in the indices. It is intended to be more memory efficient 24 * than using a HashMap to map Integers to Objects, both because it avoids 25 * auto-boxing keys and its data structure doesn't rely on an extra entry object 26 * for each mapping. 27 * 28 * <p>Note that this container keeps its mappings in an array data structure, 29 * using a binary search to find keys. The implementation is not intended to be appropriate for 30 * data structures 31 * that may contain large numbers of items. It is generally slower than a traditional 32 * HashMap, since lookups require a binary search and adds and removes require inserting 33 * and deleting entries in the array. For containers holding up to hundreds of items, 34 * the performance difference is not significant, less than 50%.</p> 35 * 36 * <p>To help with performance, the container includes an optimization when removing 37 * keys: instead of compacting its array immediately, it leaves the removed entry marked 38 * as deleted. The entry can then be re-used for the same key, or compacted later in 39 * a single garbage collection step of all removed entries. This garbage collection will 40 * need to be performed at any time the array needs to be grown or the the map size or 41 * entry values are retrieved.</p> 42 * 43 * <p>It is possible to iterate over the items in this container using 44 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using 45 * <code>keyAt(int)</code> with ascending values of the index will return the 46 * keys in ascending order, or the values corresponding to the keys in ascending 47 * order in the case of <code>valueAt(int)<code>.</p> 48 */ 49 public class SparseArray<E> implements Cloneable { 50 private static final Object DELETED = new Object(); 51 private boolean mGarbage = false; 52 53 private int[] mKeys; 54 private Object[] mValues; 55 private int mSize; 56 57 /** 58 * Creates a new SparseArray containing no mappings. 59 */ SparseArray()60 public SparseArray() { 61 this(10); 62 } 63 64 /** 65 * Creates a new SparseArray containing no mappings that will not 66 * require any additional memory allocation to store the specified 67 * number of mappings. If you supply an initial capacity of 0, the 68 * sparse array will be initialized with a light-weight representation 69 * not requiring any additional array allocations. 70 */ SparseArray(int initialCapacity)71 public SparseArray(int initialCapacity) { 72 if (initialCapacity == 0) { 73 mKeys = ContainerHelpers.EMPTY_INTS; 74 mValues = ContainerHelpers.EMPTY_OBJECTS; 75 } else { 76 initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); 77 mKeys = new int[initialCapacity]; 78 mValues = new Object[initialCapacity]; 79 } 80 mSize = 0; 81 } 82 83 @Override 84 @SuppressWarnings("unchecked") clone()85 public SparseArray<E> clone() { 86 SparseArray<E> clone = null; 87 try { 88 clone = (SparseArray<E>) super.clone(); 89 clone.mKeys = mKeys.clone(); 90 clone.mValues = mValues.clone(); 91 } catch (CloneNotSupportedException cnse) { 92 /* ignore */ 93 } 94 return clone; 95 } 96 97 /** 98 * Gets the Object mapped from the specified key, or <code>null</code> 99 * if no such mapping has been made. 100 */ get(int key)101 public E get(int key) { 102 return get(key, null); 103 } 104 105 /** 106 * Gets the Object mapped from the specified key, or the specified Object 107 * if no such mapping has been made. 108 */ 109 @SuppressWarnings("unchecked") get(int key, E valueIfKeyNotFound)110 public E get(int key, E valueIfKeyNotFound) { 111 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 112 113 if (i < 0 || mValues[i] == DELETED) { 114 return valueIfKeyNotFound; 115 } else { 116 return (E) mValues[i]; 117 } 118 } 119 120 /** 121 * Removes the mapping from the specified key, if there was any. 122 */ delete(int key)123 public void delete(int key) { 124 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 125 126 if (i >= 0) { 127 if (mValues[i] != DELETED) { 128 mValues[i] = DELETED; 129 mGarbage = true; 130 } 131 } 132 } 133 134 /** 135 * Alias for {@link #delete(int)}. 136 */ remove(int key)137 public void remove(int key) { 138 delete(key); 139 } 140 141 /** 142 * Removes the mapping at the specified index. 143 */ removeAt(int index)144 public void removeAt(int index) { 145 if (mValues[index] != DELETED) { 146 mValues[index] = DELETED; 147 mGarbage = true; 148 } 149 } 150 151 /** 152 * Remove a range of mappings as a batch. 153 * 154 * @param index Index to begin at 155 * @param size Number of mappings to remove 156 */ removeAtRange(int index, int size)157 public void removeAtRange(int index, int size) { 158 final int end = Math.min(mSize, index + size); 159 for (int i = index; i < end; i++) { 160 removeAt(i); 161 } 162 } 163 gc()164 private void gc() { 165 // Log.e("SparseArray", "gc start with " + mSize); 166 167 int n = mSize; 168 int o = 0; 169 int[] keys = mKeys; 170 Object[] values = mValues; 171 172 for (int i = 0; i < n; i++) { 173 Object val = values[i]; 174 175 if (val != DELETED) { 176 if (i != o) { 177 keys[o] = keys[i]; 178 values[o] = val; 179 values[i] = null; 180 } 181 182 o++; 183 } 184 } 185 186 mGarbage = false; 187 mSize = o; 188 189 // Log.e("SparseArray", "gc end with " + mSize); 190 } 191 192 /** 193 * Adds a mapping from the specified key to the specified value, 194 * replacing the previous mapping from the specified key if there 195 * was one. 196 */ put(int key, E value)197 public void put(int key, E value) { 198 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 199 200 if (i >= 0) { 201 mValues[i] = value; 202 } else { 203 i = ~i; 204 205 if (i < mSize && mValues[i] == DELETED) { 206 mKeys[i] = key; 207 mValues[i] = value; 208 return; 209 } 210 211 if (mGarbage && mSize >= mKeys.length) { 212 gc(); 213 214 // Search again because indices may have changed. 215 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key); 216 } 217 218 if (mSize >= mKeys.length) { 219 int n = ArrayUtils.idealIntArraySize(mSize + 1); 220 221 int[] nkeys = new int[n]; 222 Object[] nvalues = new Object[n]; 223 224 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n); 225 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); 226 System.arraycopy(mValues, 0, nvalues, 0, mValues.length); 227 228 mKeys = nkeys; 229 mValues = nvalues; 230 } 231 232 if (mSize - i != 0) { 233 // Log.e("SparseArray", "move " + (mSize - i)); 234 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); 235 System.arraycopy(mValues, i, mValues, i + 1, mSize - i); 236 } 237 238 mKeys[i] = key; 239 mValues[i] = value; 240 mSize++; 241 } 242 } 243 244 /** 245 * Returns the number of key-value mappings that this SparseArray 246 * currently stores. 247 */ size()248 public int size() { 249 if (mGarbage) { 250 gc(); 251 } 252 253 return mSize; 254 } 255 256 /** 257 * Given an index in the range <code>0...size()-1</code>, returns 258 * the key from the <code>index</code>th key-value mapping that this 259 * SparseArray stores. 260 * 261 * <p>The keys corresponding to indices in ascending order are guaranteed to 262 * be in ascending order, e.g., <code>keyAt(0)</code> will return the 263 * smallest key and <code>keyAt(size()-1)</code> will return the largest 264 * key.</p> 265 */ keyAt(int index)266 public int keyAt(int index) { 267 if (mGarbage) { 268 gc(); 269 } 270 271 return mKeys[index]; 272 } 273 274 /** 275 * Given an index in the range <code>0...size()-1</code>, returns 276 * the value from the <code>index</code>th key-value mapping that this 277 * SparseArray stores. 278 * 279 * <p>The values corresponding to indices in ascending order are guaranteed 280 * to be associated with keys in ascending order, e.g., 281 * <code>valueAt(0)</code> will return the value associated with the 282 * smallest key and <code>valueAt(size()-1)</code> will return the value 283 * associated with the largest key.</p> 284 */ 285 @SuppressWarnings("unchecked") valueAt(int index)286 public E valueAt(int index) { 287 if (mGarbage) { 288 gc(); 289 } 290 291 return (E) mValues[index]; 292 } 293 294 /** 295 * Given an index in the range <code>0...size()-1</code>, sets a new 296 * value for the <code>index</code>th key-value mapping that this 297 * SparseArray stores. 298 */ setValueAt(int index, E value)299 public void setValueAt(int index, E value) { 300 if (mGarbage) { 301 gc(); 302 } 303 304 mValues[index] = value; 305 } 306 307 /** 308 * Returns the index for which {@link #keyAt} would return the 309 * specified key, or a negative number if the specified 310 * key is not mapped. 311 */ indexOfKey(int key)312 public int indexOfKey(int key) { 313 if (mGarbage) { 314 gc(); 315 } 316 317 return ContainerHelpers.binarySearch(mKeys, mSize, key); 318 } 319 320 /** 321 * Returns an index for which {@link #valueAt} would return the 322 * specified key, or a negative number if no keys map to the 323 * specified value. 324 * <p>Beware that this is a linear search, unlike lookups by key, 325 * and that multiple keys can map to the same value and this will 326 * find only one of them. 327 * <p>Note also that unlike most collections' {@code indexOf} methods, 328 * this method compares values using {@code ==} rather than {@code equals}. 329 */ indexOfValue(E value)330 public int indexOfValue(E value) { 331 if (mGarbage) { 332 gc(); 333 } 334 335 for (int i = 0; i < mSize; i++) 336 if (mValues[i] == value) 337 return i; 338 339 return -1; 340 } 341 342 /** 343 * Removes all key-value mappings from this SparseArray. 344 */ clear()345 public void clear() { 346 int n = mSize; 347 Object[] values = mValues; 348 349 for (int i = 0; i < n; i++) { 350 values[i] = null; 351 } 352 353 mSize = 0; 354 mGarbage = false; 355 } 356 357 /** 358 * Puts a key/value pair into the array, optimizing for the case where 359 * the key is greater than all existing keys in the array. 360 */ append(int key, E value)361 public void append(int key, E value) { 362 if (mSize != 0 && key <= mKeys[mSize - 1]) { 363 put(key, value); 364 return; 365 } 366 367 if (mGarbage && mSize >= mKeys.length) { 368 gc(); 369 } 370 371 int pos = mSize; 372 if (pos >= mKeys.length) { 373 int n = ArrayUtils.idealIntArraySize(pos + 1); 374 375 int[] nkeys = new int[n]; 376 Object[] nvalues = new Object[n]; 377 378 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n); 379 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); 380 System.arraycopy(mValues, 0, nvalues, 0, mValues.length); 381 382 mKeys = nkeys; 383 mValues = nvalues; 384 } 385 386 mKeys[pos] = key; 387 mValues[pos] = value; 388 mSize = pos + 1; 389 } 390 391 /** 392 * {@inheritDoc} 393 * 394 * <p>This implementation composes a string by iterating over its mappings. If 395 * this map contains itself as a value, the string "(this Map)" 396 * will appear in its place. 397 */ 398 @Override toString()399 public String toString() { 400 if (size() <= 0) { 401 return "{}"; 402 } 403 404 StringBuilder buffer = new StringBuilder(mSize * 28); 405 buffer.append('{'); 406 for (int i=0; i<mSize; i++) { 407 if (i > 0) { 408 buffer.append(", "); 409 } 410 int key = keyAt(i); 411 buffer.append(key); 412 buffer.append('='); 413 Object value = valueAt(i); 414 if (value != this) { 415 buffer.append(value); 416 } else { 417 buffer.append("(this Map)"); 418 } 419 } 420 buffer.append('}'); 421 return buffer.toString(); 422 } 423 } 424