blob: af18caa0e1220a2e1db9cf05c56214b39f5f550e [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;
Adam Lesinski776abc22014-03-07 11:30:59 -050020import com.android.internal.util.GrowingArrayUtils;
21
22import libcore.util.EmptyArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24/**
Laura Davise27c3512018-07-26 15:21:45 -070025 * <code>SparseArray</code> maps integers to Objects and, unlike a normal array of Objects,
26 * its indices can contain gaps. <code>SparseArray</code> is intended to be more memory-efficient
27 * than a
28 * <a href="/reference/java/util/HashMap"><code>HashMap</code></a>, because it avoids
Dianne Hackbornb993f412013-07-12 17:46:45 -070029 * auto-boxing keys and its data structure doesn't rely on an extra entry object
30 * for each mapping.
31 *
32 * <p>Note that this container keeps its mappings in an array data structure,
Laura Davise27c3512018-07-26 15:21:45 -070033 * using a binary search to find keys. The implementation is not intended to be appropriate for
Dianne Hackbornb993f412013-07-12 17:46:45 -070034 * data structures
Laura Davise27c3512018-07-26 15:21:45 -070035 * that may contain large numbers of items. It is generally slower than a
36 * <code>HashMap</code> because lookups require a binary search,
37 * and adds and removes require inserting
38 * and deleting entries in the array. For containers holding up to hundreds of items,
39 * the performance difference is less than 50%.
Dianne Hackbornb993f412013-07-12 17:46:45 -070040 *
41 * <p>To help with performance, the container includes an optimization when removing
42 * keys: instead of compacting its array immediately, it leaves the removed entry marked
Laura Davise27c3512018-07-26 15:21:45 -070043 * as deleted. The entry can then be re-used for the same key or compacted later in
44 * a single garbage collection of all removed entries. This garbage collection
45 * must be performed whenever the array needs to be grown, or when the map size or
46 * entry values are retrieved.
Flavio Lerda57713022013-09-08 18:04:58 +010047 *
48 * <p>It is possible to iterate over the items in this container using
49 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
Laura Davise27c3512018-07-26 15:21:45 -070050 * <code>keyAt(int)</code> with ascending values of the index returns the
51 * keys in ascending order. In the case of <code>valueAt(int)</code>, the
52 * values corresponding to the keys are returned in ascending order.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070054public class SparseArray<E> implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055 private static final Object DELETED = new Object();
56 private boolean mGarbage = false;
57
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070058 private int[] mKeys;
59 private Object[] mValues;
60 private int mSize;
61
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 /**
63 * Creates a new SparseArray containing no mappings.
64 */
65 public SparseArray() {
66 this(10);
67 }
68
69 /**
70 * Creates a new SparseArray containing no mappings that will not
71 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070072 * number of mappings. If you supply an initial capacity of 0, the
73 * sparse array will be initialized with a light-weight representation
74 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 */
76 public SparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070077 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050078 mKeys = EmptyArray.INT;
79 mValues = EmptyArray.OBJECT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070080 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050081 mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
82 mKeys = new int[mValues.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 mSize = 0;
85 }
86
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070087 @Override
88 @SuppressWarnings("unchecked")
89 public SparseArray<E> clone() {
90 SparseArray<E> clone = null;
91 try {
92 clone = (SparseArray<E>) super.clone();
93 clone.mKeys = mKeys.clone();
94 clone.mValues = mValues.clone();
95 } catch (CloneNotSupportedException cnse) {
96 /* ignore */
97 }
98 return clone;
99 }
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 /**
102 * Gets the Object mapped from the specified key, or <code>null</code>
103 * if no such mapping has been made.
104 */
105 public E get(int key) {
106 return get(key, null);
107 }
108
109 /**
110 * Gets the Object mapped from the specified key, or the specified Object
111 * if no such mapping has been made.
112 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700113 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 public E get(int key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700115 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
117 if (i < 0 || mValues[i] == DELETED) {
118 return valueIfKeyNotFound;
119 } else {
120 return (E) mValues[i];
121 }
122 }
123
124 /**
125 * Removes the mapping from the specified key, if there was any.
126 */
127 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700128 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
130 if (i >= 0) {
131 if (mValues[i] != DELETED) {
132 mValues[i] = DELETED;
133 mGarbage = true;
134 }
135 }
136 }
137
138 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700139 * @hide
140 * Removes the mapping from the specified key, if there was any, returning the old value.
141 */
142 public E removeReturnOld(int key) {
143 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
144
145 if (i >= 0) {
146 if (mValues[i] != DELETED) {
147 final E old = (E) mValues[i];
148 mValues[i] = DELETED;
149 mGarbage = true;
150 return old;
151 }
152 }
153 return null;
154 }
155
156 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 * Alias for {@link #delete(int)}.
158 */
159 public void remove(int key) {
160 delete(key);
161 }
162
Dianne Hackbornc8017682010-07-06 13:34:38 -0700163 /**
164 * Removes the mapping at the specified index.
Phil Weaveradaafb22016-05-19 10:32:52 -0700165 *
166 * <p>For indices outside of the range <code>0...size()-1</code>,
167 * the behavior is undefined.</p>
Dianne Hackbornc8017682010-07-06 13:34:38 -0700168 */
169 public void removeAt(int index) {
170 if (mValues[index] != DELETED) {
171 mValues[index] = DELETED;
172 mGarbage = true;
173 }
174 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700175
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700176 /**
177 * Remove a range of mappings as a batch.
178 *
179 * @param index Index to begin at
180 * @param size Number of mappings to remove
Phil Weaveradaafb22016-05-19 10:32:52 -0700181 *
182 * <p>For indices outside of the range <code>0...size()-1</code>,
183 * the behavior is undefined.</p>
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700184 */
185 public void removeAtRange(int index, int size) {
186 final int end = Math.min(mSize, index + size);
187 for (int i = index; i < end; i++) {
188 removeAt(i);
189 }
190 }
191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private void gc() {
193 // Log.e("SparseArray", "gc start with " + mSize);
194
195 int n = mSize;
196 int o = 0;
197 int[] keys = mKeys;
198 Object[] values = mValues;
199
200 for (int i = 0; i < n; i++) {
201 Object val = values[i];
202
203 if (val != DELETED) {
204 if (i != o) {
205 keys[o] = keys[i];
206 values[o] = val;
Svetoslav Ganovd116d7c2011-11-21 18:41:59 -0800207 values[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 }
209
210 o++;
211 }
212 }
213
214 mGarbage = false;
215 mSize = o;
216
217 // Log.e("SparseArray", "gc end with " + mSize);
218 }
219
220 /**
221 * Adds a mapping from the specified key to the specified value,
222 * replacing the previous mapping from the specified key if there
223 * was one.
224 */
225 public void put(int key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700226 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
228 if (i >= 0) {
229 mValues[i] = value;
230 } else {
231 i = ~i;
232
233 if (i < mSize && mValues[i] == DELETED) {
234 mKeys[i] = key;
235 mValues[i] = value;
236 return;
237 }
238
239 if (mGarbage && mSize >= mKeys.length) {
240 gc();
241
242 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700243 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245
Adam Lesinski776abc22014-03-07 11:30:59 -0500246 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
247 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mSize++;
249 }
250 }
251
252 /**
253 * Returns the number of key-value mappings that this SparseArray
254 * currently stores.
255 */
256 public int size() {
257 if (mGarbage) {
258 gc();
259 }
260
261 return mSize;
262 }
263
264 /**
265 * Given an index in the range <code>0...size()-1</code>, returns
266 * the key from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700267 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100268 *
269 * <p>The keys corresponding to indices in ascending order are guaranteed to
270 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
271 * smallest key and <code>keyAt(size()-1)</code> will return the largest
272 * key.</p>
Phil Weaveradaafb22016-05-19 10:32:52 -0700273 *
274 * <p>For indices outside of the range <code>0...size()-1</code>,
275 * the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 */
277 public int keyAt(int index) {
278 if (mGarbage) {
279 gc();
280 }
281
282 return mKeys[index];
283 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 /**
286 * Given an index in the range <code>0...size()-1</code>, returns
287 * the value from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700288 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100289 *
290 * <p>The values corresponding to indices in ascending order are guaranteed
291 * to be associated with keys in ascending order, e.g.,
292 * <code>valueAt(0)</code> will return the value associated with the
293 * smallest key and <code>valueAt(size()-1)</code> will return the value
294 * associated with the largest key.</p>
Phil Weaveradaafb22016-05-19 10:32:52 -0700295 *
296 * <p>For indices outside of the range <code>0...size()-1</code>,
297 * the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700299 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 public E valueAt(int index) {
301 if (mGarbage) {
302 gc();
303 }
304
305 return (E) mValues[index];
306 }
307
308 /**
309 * Given an index in the range <code>0...size()-1</code>, sets a new
310 * value for the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700311 * SparseArray stores.
Phil Weaveradaafb22016-05-19 10:32:52 -0700312 *
313 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 */
315 public void setValueAt(int index, E value) {
316 if (mGarbage) {
317 gc();
318 }
319
320 mValues[index] = value;
321 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 /**
324 * Returns the index for which {@link #keyAt} would return the
325 * specified key, or a negative number if the specified
326 * key is not mapped.
327 */
328 public int indexOfKey(int key) {
329 if (mGarbage) {
330 gc();
331 }
332
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700333 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 }
335
336 /**
337 * Returns an index for which {@link #valueAt} would return the
Laura Davise27c3512018-07-26 15:21:45 -0700338 * specified value, or a negative number if no keys map to the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 * specified value.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700340 * <p>Beware that this is a linear search, unlike lookups by key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * and that multiple keys can map to the same value and this will
342 * find only one of them.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700343 * <p>Note also that unlike most collections' {@code indexOf} methods,
344 * this method compares values using {@code ==} rather than {@code equals}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 */
346 public int indexOfValue(E value) {
347 if (mGarbage) {
348 gc();
349 }
350
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700351 for (int i = 0; i < mSize; i++) {
352 if (mValues[i] == value) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 return i;
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700354 }
355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
357 return -1;
358 }
359
360 /**
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700361 * Returns an index for which {@link #valueAt} would return the
Laura Davise27c3512018-07-26 15:21:45 -0700362 * specified value, or a negative number if no keys map to the
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700363 * specified value.
364 * <p>Beware that this is a linear search, unlike lookups by key,
365 * and that multiple keys can map to the same value and this will
366 * find only one of them.
367 * <p>Note also that this method uses {@code equals} unlike {@code indexOfValue}.
Suprabh Shukla0693ff62017-03-23 16:09:27 -0700368 * @hide
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700369 */
370 public int indexOfValueByValue(E value) {
371 if (mGarbage) {
372 gc();
373 }
374
375 for (int i = 0; i < mSize; i++) {
376 if (value == null) {
377 if (mValues[i] == null) {
378 return i;
379 }
380 } else {
381 if (value.equals(mValues[i])) {
382 return i;
383 }
384 }
385 }
386 return -1;
387 }
388
389 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 * Removes all key-value mappings from this SparseArray.
391 */
392 public void clear() {
393 int n = mSize;
394 Object[] values = mValues;
395
396 for (int i = 0; i < n; i++) {
397 values[i] = null;
398 }
399
400 mSize = 0;
401 mGarbage = false;
402 }
403
404 /**
405 * Puts a key/value pair into the array, optimizing for the case where
406 * the key is greater than all existing keys in the array.
407 */
408 public void append(int key, E value) {
409 if (mSize != 0 && key <= mKeys[mSize - 1]) {
410 put(key, value);
411 return;
412 }
413
414 if (mGarbage && mSize >= mKeys.length) {
415 gc();
416 }
417
Adam Lesinski776abc22014-03-07 11:30:59 -0500418 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
419 mValues = GrowingArrayUtils.append(mValues, mSize, value);
420 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700422
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700423 /**
424 * {@inheritDoc}
425 *
426 * <p>This implementation composes a string by iterating over its mappings. If
427 * this map contains itself as a value, the string "(this Map)"
428 * will appear in its place.
429 */
430 @Override
431 public String toString() {
432 if (size() <= 0) {
433 return "{}";
434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700436 StringBuilder buffer = new StringBuilder(mSize * 28);
437 buffer.append('{');
438 for (int i=0; i<mSize; i++) {
439 if (i > 0) {
440 buffer.append(", ");
441 }
442 int key = keyAt(i);
443 buffer.append(key);
444 buffer.append('=');
445 Object value = valueAt(i);
446 if (value != this) {
447 buffer.append(value);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700448 } else {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700449 buffer.append("(this Map)");
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700452 buffer.append('}');
453 return buffer.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455}