blob: 67dfb02a0b9545aa6c0fd44376d9470fc96e9632 [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
Kweku Adams17d453e2019-03-05 15:30:42 -080019import android.annotation.UnsupportedAppUsage;
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050022import com.android.internal.util.GrowingArrayUtils;
23
24import libcore.util.EmptyArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26/**
Laura Davise27c3512018-07-26 15:21:45 -070027 * <code>SparseArray</code> maps integers to Objects and, unlike a normal array of Objects,
28 * its indices can contain gaps. <code>SparseArray</code> is intended to be more memory-efficient
29 * than a
30 * <a href="/reference/java/util/HashMap"><code>HashMap</code></a>, because it avoids
Dianne Hackbornb993f412013-07-12 17:46:45 -070031 * auto-boxing keys and its data structure doesn't rely on an extra entry object
32 * for each mapping.
33 *
34 * <p>Note that this container keeps its mappings in an array data structure,
Laura Davise27c3512018-07-26 15:21:45 -070035 * using a binary search to find keys. The implementation is not intended to be appropriate for
Dianne Hackbornb993f412013-07-12 17:46:45 -070036 * data structures
Laura Davise27c3512018-07-26 15:21:45 -070037 * that may contain large numbers of items. It is generally slower than a
38 * <code>HashMap</code> because lookups require a binary search,
39 * and adds and removes require inserting
40 * and deleting entries in the array. For containers holding up to hundreds of items,
41 * the performance difference is less than 50%.
Dianne Hackbornb993f412013-07-12 17:46:45 -070042 *
43 * <p>To help with performance, the container includes an optimization when removing
44 * keys: instead of compacting its array immediately, it leaves the removed entry marked
Laura Davise27c3512018-07-26 15:21:45 -070045 * as deleted. The entry can then be re-used for the same key or compacted later in
46 * a single garbage collection of all removed entries. This garbage collection
47 * must be performed whenever the array needs to be grown, or when the map size or
48 * entry values are retrieved.
Flavio Lerda57713022013-09-08 18:04:58 +010049 *
50 * <p>It is possible to iterate over the items in this container using
51 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
Laura Davise27c3512018-07-26 15:21:45 -070052 * <code>keyAt(int)</code> with ascending values of the index returns the
53 * keys in ascending order. In the case of <code>valueAt(int)</code>, the
54 * values corresponding to the keys are returned in ascending order.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070056public class SparseArray<E> implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057 private static final Object DELETED = new Object();
58 private boolean mGarbage = false;
59
Jake Whartona8a04352018-09-29 01:52:24 -040060 @UnsupportedAppUsage(maxTargetSdk = 28) // Use keyAt(int)
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070061 private int[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -040062 @UnsupportedAppUsage(maxTargetSdk = 28) // Use valueAt(int), setValueAt(int, E)
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070063 private Object[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -040064 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size()
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070065 private int mSize;
66
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 /**
68 * Creates a new SparseArray containing no mappings.
69 */
70 public SparseArray() {
71 this(10);
72 }
73
74 /**
75 * Creates a new SparseArray containing no mappings that will not
76 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070077 * number of mappings. If you supply an initial capacity of 0, the
78 * sparse array will be initialized with a light-weight representation
79 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 */
81 public SparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070082 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050083 mKeys = EmptyArray.INT;
84 mValues = EmptyArray.OBJECT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070085 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050086 mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
87 mKeys = new int[mValues.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 mSize = 0;
90 }
91
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070092 @Override
93 @SuppressWarnings("unchecked")
94 public SparseArray<E> clone() {
95 SparseArray<E> clone = null;
96 try {
97 clone = (SparseArray<E>) super.clone();
98 clone.mKeys = mKeys.clone();
99 clone.mValues = mValues.clone();
100 } catch (CloneNotSupportedException cnse) {
101 /* ignore */
102 }
103 return clone;
104 }
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 /**
107 * Gets the Object mapped from the specified key, or <code>null</code>
108 * if no such mapping has been made.
109 */
110 public E get(int key) {
111 return get(key, null);
112 }
113
114 /**
115 * Gets the Object mapped from the specified key, or the specified Object
116 * if no such mapping has been made.
117 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700118 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 public E get(int key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700120 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
122 if (i < 0 || mValues[i] == DELETED) {
123 return valueIfKeyNotFound;
124 } else {
125 return (E) mValues[i];
126 }
127 }
128
129 /**
130 * Removes the mapping from the specified key, if there was any.
131 */
132 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700133 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
135 if (i >= 0) {
136 if (mValues[i] != DELETED) {
137 mValues[i] = DELETED;
138 mGarbage = true;
139 }
140 }
141 }
142
143 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700144 * @hide
145 * Removes the mapping from the specified key, if there was any, returning the old value.
146 */
147 public E removeReturnOld(int key) {
148 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
149
150 if (i >= 0) {
151 if (mValues[i] != DELETED) {
152 final E old = (E) mValues[i];
153 mValues[i] = DELETED;
154 mGarbage = true;
155 return old;
156 }
157 }
158 return null;
159 }
160
161 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 * Alias for {@link #delete(int)}.
163 */
164 public void remove(int key) {
165 delete(key);
166 }
167
Dianne Hackbornc8017682010-07-06 13:34:38 -0700168 /**
169 * Removes the mapping at the specified index.
Phil Weaveradaafb22016-05-19 10:32:52 -0700170 *
171 * <p>For indices outside of the range <code>0...size()-1</code>,
172 * the behavior is undefined.</p>
Dianne Hackbornc8017682010-07-06 13:34:38 -0700173 */
174 public void removeAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800175 if (index >= mSize) {
176 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
177 throw new ArrayIndexOutOfBoundsException(index);
178 }
Dianne Hackbornc8017682010-07-06 13:34:38 -0700179 if (mValues[index] != DELETED) {
180 mValues[index] = DELETED;
181 mGarbage = true;
182 }
183 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700184
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700185 /**
186 * Remove a range of mappings as a batch.
187 *
188 * @param index Index to begin at
189 * @param size Number of mappings to remove
Phil Weaveradaafb22016-05-19 10:32:52 -0700190 *
191 * <p>For indices outside of the range <code>0...size()-1</code>,
192 * the behavior is undefined.</p>
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700193 */
194 public void removeAtRange(int index, int size) {
195 final int end = Math.min(mSize, index + size);
196 for (int i = index; i < end; i++) {
197 removeAt(i);
198 }
199 }
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private void gc() {
202 // Log.e("SparseArray", "gc start with " + mSize);
203
204 int n = mSize;
205 int o = 0;
206 int[] keys = mKeys;
207 Object[] values = mValues;
208
209 for (int i = 0; i < n; i++) {
210 Object val = values[i];
211
212 if (val != DELETED) {
213 if (i != o) {
214 keys[o] = keys[i];
215 values[o] = val;
Svetoslav Ganovd116d7c2011-11-21 18:41:59 -0800216 values[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 }
218
219 o++;
220 }
221 }
222
223 mGarbage = false;
224 mSize = o;
225
226 // Log.e("SparseArray", "gc end with " + mSize);
227 }
228
229 /**
230 * Adds a mapping from the specified key to the specified value,
231 * replacing the previous mapping from the specified key if there
232 * was one.
233 */
234 public void put(int key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700235 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
237 if (i >= 0) {
238 mValues[i] = value;
239 } else {
240 i = ~i;
241
242 if (i < mSize && mValues[i] == DELETED) {
243 mKeys[i] = key;
244 mValues[i] = value;
245 return;
246 }
247
248 if (mGarbage && mSize >= mKeys.length) {
249 gc();
250
251 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700252 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 }
254
Adam Lesinski776abc22014-03-07 11:30:59 -0500255 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
256 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 mSize++;
258 }
259 }
260
261 /**
262 * Returns the number of key-value mappings that this SparseArray
263 * currently stores.
264 */
265 public int size() {
266 if (mGarbage) {
267 gc();
268 }
269
270 return mSize;
271 }
272
273 /**
274 * Given an index in the range <code>0...size()-1</code>, returns
275 * the key from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700276 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100277 *
278 * <p>The keys corresponding to indices in ascending order are guaranteed to
279 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
280 * smallest key and <code>keyAt(size()-1)</code> will return the largest
281 * key.</p>
Phil Weaveradaafb22016-05-19 10:32:52 -0700282 *
283 * <p>For indices outside of the range <code>0...size()-1</code>,
284 * the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 */
286 public int keyAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800287 if (index >= mSize) {
288 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
289 throw new ArrayIndexOutOfBoundsException(index);
290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 if (mGarbage) {
292 gc();
293 }
294
295 return mKeys[index];
296 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 /**
299 * Given an index in the range <code>0...size()-1</code>, returns
300 * the value from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700301 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100302 *
303 * <p>The values corresponding to indices in ascending order are guaranteed
304 * to be associated with keys in ascending order, e.g.,
305 * <code>valueAt(0)</code> will return the value associated with the
306 * smallest key and <code>valueAt(size()-1)</code> will return the value
307 * associated with the largest key.</p>
Phil Weaveradaafb22016-05-19 10:32:52 -0700308 *
309 * <p>For indices outside of the range <code>0...size()-1</code>,
310 * the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700312 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 public E valueAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800314 if (index >= mSize) {
315 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
316 throw new ArrayIndexOutOfBoundsException(index);
317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 if (mGarbage) {
319 gc();
320 }
321
322 return (E) mValues[index];
323 }
324
325 /**
326 * Given an index in the range <code>0...size()-1</code>, sets a new
327 * value for the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700328 * SparseArray stores.
Phil Weaveradaafb22016-05-19 10:32:52 -0700329 *
330 * <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 -0800331 */
332 public void setValueAt(int index, E value) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800333 if (index >= mSize) {
334 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
335 throw new ArrayIndexOutOfBoundsException(index);
336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 if (mGarbage) {
338 gc();
339 }
340
341 mValues[index] = value;
342 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 /**
345 * Returns the index for which {@link #keyAt} would return the
346 * specified key, or a negative number if the specified
347 * key is not mapped.
348 */
349 public int indexOfKey(int key) {
350 if (mGarbage) {
351 gc();
352 }
353
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700354 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 }
356
357 /**
358 * Returns an index for which {@link #valueAt} would return the
Laura Davise27c3512018-07-26 15:21:45 -0700359 * specified value, or a negative number if no keys map to the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 * specified value.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700361 * <p>Beware that this is a linear search, unlike lookups by key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 * and that multiple keys can map to the same value and this will
363 * find only one of them.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700364 * <p>Note also that unlike most collections' {@code indexOf} methods,
365 * this method compares values using {@code ==} rather than {@code equals}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 */
367 public int indexOfValue(E value) {
368 if (mGarbage) {
369 gc();
370 }
371
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700372 for (int i = 0; i < mSize; i++) {
373 if (mValues[i] == value) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 return i;
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700375 }
376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377
378 return -1;
379 }
380
381 /**
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700382 * Returns an index for which {@link #valueAt} would return the
Laura Davise27c3512018-07-26 15:21:45 -0700383 * specified value, or a negative number if no keys map to the
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700384 * specified value.
385 * <p>Beware that this is a linear search, unlike lookups by key,
386 * and that multiple keys can map to the same value and this will
387 * find only one of them.
388 * <p>Note also that this method uses {@code equals} unlike {@code indexOfValue}.
Suprabh Shukla0693ff62017-03-23 16:09:27 -0700389 * @hide
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700390 */
391 public int indexOfValueByValue(E value) {
392 if (mGarbage) {
393 gc();
394 }
395
396 for (int i = 0; i < mSize; i++) {
397 if (value == null) {
398 if (mValues[i] == null) {
399 return i;
400 }
401 } else {
402 if (value.equals(mValues[i])) {
403 return i;
404 }
405 }
406 }
407 return -1;
408 }
409
410 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 * Removes all key-value mappings from this SparseArray.
412 */
413 public void clear() {
414 int n = mSize;
415 Object[] values = mValues;
416
417 for (int i = 0; i < n; i++) {
418 values[i] = null;
419 }
420
421 mSize = 0;
422 mGarbage = false;
423 }
424
425 /**
426 * Puts a key/value pair into the array, optimizing for the case where
427 * the key is greater than all existing keys in the array.
428 */
429 public void append(int key, E value) {
430 if (mSize != 0 && key <= mKeys[mSize - 1]) {
431 put(key, value);
432 return;
433 }
434
435 if (mGarbage && mSize >= mKeys.length) {
436 gc();
437 }
438
Adam Lesinski776abc22014-03-07 11:30:59 -0500439 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
440 mValues = GrowingArrayUtils.append(mValues, mSize, value);
441 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700443
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700444 /**
445 * {@inheritDoc}
446 *
447 * <p>This implementation composes a string by iterating over its mappings. If
448 * this map contains itself as a value, the string "(this Map)"
449 * will appear in its place.
450 */
451 @Override
452 public String toString() {
453 if (size() <= 0) {
454 return "{}";
455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700457 StringBuilder buffer = new StringBuilder(mSize * 28);
458 buffer.append('{');
459 for (int i=0; i<mSize; i++) {
460 if (i > 0) {
461 buffer.append(", ");
462 }
463 int key = keyAt(i);
464 buffer.append(key);
465 buffer.append('=');
466 Object value = valueAt(i);
467 if (value != this) {
468 buffer.append(value);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700469 } else {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700470 buffer.append("(this Map)");
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700473 buffer.append('}');
474 return buffer.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476}