blob: 6e6609051aaec8b815243f8d1277e163bf20d198 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
17package android.util;
18
19import com.android.internal.util.ArrayUtils;
20
21/**
22 * SparseArrays map integers to Objects. Unlike a normal array of Objects,
Dianne Hackbornb993f412013-07-12 17:46:45 -070023 * 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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070043public class SparseArray<E> implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 private static final Object DELETED = new Object();
45 private boolean mGarbage = false;
46
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070047 private int[] mKeys;
48 private Object[] mValues;
49 private int mSize;
50
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 /**
52 * Creates a new SparseArray containing no mappings.
53 */
54 public SparseArray() {
55 this(10);
56 }
57
58 /**
59 * Creates a new SparseArray containing no mappings that will not
60 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070061 * number of mappings. If you supply an initial capacity of 0, the
62 * sparse array will be initialized with a light-weight representation
63 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 */
65 public SparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070066 if (initialCapacity == 0) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070067 mKeys = ContainerHelpers.EMPTY_INTS;
68 mValues = ContainerHelpers.EMPTY_OBJECTS;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070069 } else {
70 initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
71 mKeys = new int[initialCapacity];
72 mValues = new Object[initialCapacity];
73 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 mSize = 0;
75 }
76
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070077 @Override
78 @SuppressWarnings("unchecked")
79 public SparseArray<E> clone() {
80 SparseArray<E> clone = null;
81 try {
82 clone = (SparseArray<E>) super.clone();
83 clone.mKeys = mKeys.clone();
84 clone.mValues = mValues.clone();
85 } catch (CloneNotSupportedException cnse) {
86 /* ignore */
87 }
88 return clone;
89 }
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 /**
92 * Gets the Object mapped from the specified key, or <code>null</code>
93 * if no such mapping has been made.
94 */
95 public E get(int key) {
96 return get(key, null);
97 }
98
99 /**
100 * Gets the Object mapped from the specified key, or the specified Object
101 * if no such mapping has been made.
102 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700103 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 public E get(int key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700105 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
107 if (i < 0 || mValues[i] == DELETED) {
108 return valueIfKeyNotFound;
109 } else {
110 return (E) mValues[i];
111 }
112 }
113
114 /**
115 * Removes the mapping from the specified key, if there was any.
116 */
117 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700118 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
120 if (i >= 0) {
121 if (mValues[i] != DELETED) {
122 mValues[i] = DELETED;
123 mGarbage = true;
124 }
125 }
126 }
127
128 /**
129 * Alias for {@link #delete(int)}.
130 */
131 public void remove(int key) {
132 delete(key);
133 }
134
Dianne Hackbornc8017682010-07-06 13:34:38 -0700135 /**
136 * Removes the mapping at the specified index.
137 */
138 public void removeAt(int index) {
139 if (mValues[index] != DELETED) {
140 mValues[index] = DELETED;
141 mGarbage = true;
142 }
143 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700144
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700145 /**
146 * Remove a range of mappings as a batch.
147 *
148 * @param index Index to begin at
149 * @param size Number of mappings to remove
150 */
151 public void removeAtRange(int index, int size) {
152 final int end = Math.min(mSize, index + size);
153 for (int i = index; i < end; i++) {
154 removeAt(i);
155 }
156 }
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private void gc() {
159 // Log.e("SparseArray", "gc start with " + mSize);
160
161 int n = mSize;
162 int o = 0;
163 int[] keys = mKeys;
164 Object[] values = mValues;
165
166 for (int i = 0; i < n; i++) {
167 Object val = values[i];
168
169 if (val != DELETED) {
170 if (i != o) {
171 keys[o] = keys[i];
172 values[o] = val;
Svetoslav Ganovd116d7c2011-11-21 18:41:59 -0800173 values[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 }
175
176 o++;
177 }
178 }
179
180 mGarbage = false;
181 mSize = o;
182
183 // Log.e("SparseArray", "gc end with " + mSize);
184 }
185
186 /**
187 * Adds a mapping from the specified key to the specified value,
188 * replacing the previous mapping from the specified key if there
189 * was one.
190 */
191 public void put(int key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700192 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 if (i >= 0) {
195 mValues[i] = value;
196 } else {
197 i = ~i;
198
199 if (i < mSize && mValues[i] == DELETED) {
200 mKeys[i] = key;
201 mValues[i] = value;
202 return;
203 }
204
205 if (mGarbage && mSize >= mKeys.length) {
206 gc();
207
208 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700209 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 }
211
212 if (mSize >= mKeys.length) {
213 int n = ArrayUtils.idealIntArraySize(mSize + 1);
214
215 int[] nkeys = new int[n];
216 Object[] nvalues = new Object[n];
217
218 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
219 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
220 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
221
222 mKeys = nkeys;
223 mValues = nvalues;
224 }
225
226 if (mSize - i != 0) {
227 // Log.e("SparseArray", "move " + (mSize - i));
228 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
229 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
230 }
231
232 mKeys[i] = key;
233 mValues[i] = value;
234 mSize++;
235 }
236 }
237
238 /**
239 * Returns the number of key-value mappings that this SparseArray
240 * currently stores.
241 */
242 public int size() {
243 if (mGarbage) {
244 gc();
245 }
246
247 return mSize;
248 }
249
250 /**
251 * Given an index in the range <code>0...size()-1</code>, returns
252 * the key from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700253 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 */
255 public int keyAt(int index) {
256 if (mGarbage) {
257 gc();
258 }
259
260 return mKeys[index];
261 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 /**
264 * Given an index in the range <code>0...size()-1</code>, returns
265 * the value from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700266 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700268 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 public E valueAt(int index) {
270 if (mGarbage) {
271 gc();
272 }
273
274 return (E) mValues[index];
275 }
276
277 /**
278 * Given an index in the range <code>0...size()-1</code>, sets a new
279 * value for the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700280 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 */
282 public void setValueAt(int index, E value) {
283 if (mGarbage) {
284 gc();
285 }
286
287 mValues[index] = value;
288 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 /**
291 * Returns the index for which {@link #keyAt} would return the
292 * specified key, or a negative number if the specified
293 * key is not mapped.
294 */
295 public int indexOfKey(int key) {
296 if (mGarbage) {
297 gc();
298 }
299
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700300 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
303 /**
304 * Returns an index for which {@link #valueAt} would return the
305 * specified key, or a negative number if no keys map to the
306 * specified value.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700307 * <p>Beware that this is a linear search, unlike lookups by key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * and that multiple keys can map to the same value and this will
309 * find only one of them.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700310 * <p>Note also that unlike most collections' {@code indexOf} methods,
311 * this method compares values using {@code ==} rather than {@code equals}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 */
313 public int indexOfValue(E value) {
314 if (mGarbage) {
315 gc();
316 }
317
318 for (int i = 0; i < mSize; i++)
319 if (mValues[i] == value)
320 return i;
321
322 return -1;
323 }
324
325 /**
326 * Removes all key-value mappings from this SparseArray.
327 */
328 public void clear() {
329 int n = mSize;
330 Object[] values = mValues;
331
332 for (int i = 0; i < n; i++) {
333 values[i] = null;
334 }
335
336 mSize = 0;
337 mGarbage = false;
338 }
339
340 /**
341 * Puts a key/value pair into the array, optimizing for the case where
342 * the key is greater than all existing keys in the array.
343 */
344 public void append(int key, E value) {
345 if (mSize != 0 && key <= mKeys[mSize - 1]) {
346 put(key, value);
347 return;
348 }
349
350 if (mGarbage && mSize >= mKeys.length) {
351 gc();
352 }
353
354 int pos = mSize;
355 if (pos >= mKeys.length) {
356 int n = ArrayUtils.idealIntArraySize(pos + 1);
357
358 int[] nkeys = new int[n];
359 Object[] nvalues = new Object[n];
360
361 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
362 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
363 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
364
365 mKeys = nkeys;
366 mValues = nvalues;
367 }
368
369 mKeys[pos] = key;
370 mValues[pos] = value;
371 mSize = pos + 1;
372 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700373
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700374 /**
375 * {@inheritDoc}
376 *
377 * <p>This implementation composes a string by iterating over its mappings. If
378 * this map contains itself as a value, the string "(this Map)"
379 * will appear in its place.
380 */
381 @Override
382 public String toString() {
383 if (size() <= 0) {
384 return "{}";
385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700387 StringBuilder buffer = new StringBuilder(mSize * 28);
388 buffer.append('{');
389 for (int i=0; i<mSize; i++) {
390 if (i > 0) {
391 buffer.append(", ");
392 }
393 int key = keyAt(i);
394 buffer.append(key);
395 buffer.append('=');
396 Object value = valueAt(i);
397 if (value != this) {
398 buffer.append(value);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700399 } else {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700400 buffer.append("(this Map)");
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700403 buffer.append('}');
404 return buffer.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406}