blob: 89ea2d35fc2f4abdd68d5bb53d502b03d21cf3b7 [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
Mathew Inwood4eb56ab2018-08-14 17:24:32 +010022import android.annotation.UnsupportedAppUsage;
Adam Lesinski776abc22014-03-07 11:30:59 -050023import libcore.util.EmptyArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25/**
Laura Davise27c3512018-07-26 15:21:45 -070026 * <code>SparseArray</code> maps integers to Objects and, unlike a normal array of Objects,
27 * its indices can contain gaps. <code>SparseArray</code> is intended to be more memory-efficient
28 * than a
29 * <a href="/reference/java/util/HashMap"><code>HashMap</code></a>, because it avoids
Dianne Hackbornb993f412013-07-12 17:46:45 -070030 * auto-boxing keys and its data structure doesn't rely on an extra entry object
31 * for each mapping.
32 *
33 * <p>Note that this container keeps its mappings in an array data structure,
Laura Davise27c3512018-07-26 15:21:45 -070034 * using a binary search to find keys. The implementation is not intended to be appropriate for
Dianne Hackbornb993f412013-07-12 17:46:45 -070035 * data structures
Laura Davise27c3512018-07-26 15:21:45 -070036 * that may contain large numbers of items. It is generally slower than a
37 * <code>HashMap</code> because lookups require a binary search,
38 * and adds and removes require inserting
39 * and deleting entries in the array. For containers holding up to hundreds of items,
40 * the performance difference is less than 50%.
Dianne Hackbornb993f412013-07-12 17:46:45 -070041 *
42 * <p>To help with performance, the container includes an optimization when removing
43 * keys: instead of compacting its array immediately, it leaves the removed entry marked
Laura Davise27c3512018-07-26 15:21:45 -070044 * as deleted. The entry can then be re-used for the same key or compacted later in
45 * a single garbage collection of all removed entries. This garbage collection
46 * must be performed whenever the array needs to be grown, or when the map size or
47 * entry values are retrieved.
Flavio Lerda57713022013-09-08 18:04:58 +010048 *
49 * <p>It is possible to iterate over the items in this container using
50 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
Laura Davise27c3512018-07-26 15:21:45 -070051 * <code>keyAt(int)</code> with ascending values of the index returns the
52 * keys in ascending order. In the case of <code>valueAt(int)</code>, the
53 * values corresponding to the keys are returned in ascending order.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070055public class SparseArray<E> implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 private static final Object DELETED = new Object();
57 private boolean mGarbage = false;
58
Jake Whartona8a04352018-09-29 01:52:24 -040059 @UnsupportedAppUsage(maxTargetSdk = 28) // Use keyAt(int)
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070060 private int[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -040061 @UnsupportedAppUsage(maxTargetSdk = 28) // Use valueAt(int), setValueAt(int, E)
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070062 private Object[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -040063 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size()
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070064 private int mSize;
65
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 /**
67 * Creates a new SparseArray containing no mappings.
68 */
69 public SparseArray() {
70 this(10);
71 }
72
73 /**
74 * Creates a new SparseArray containing no mappings that will not
75 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070076 * number of mappings. If you supply an initial capacity of 0, the
77 * sparse array will be initialized with a light-weight representation
78 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 */
80 public SparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070081 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050082 mKeys = EmptyArray.INT;
83 mValues = EmptyArray.OBJECT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070084 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050085 mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
86 mKeys = new int[mValues.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 mSize = 0;
89 }
90
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070091 @Override
92 @SuppressWarnings("unchecked")
93 public SparseArray<E> clone() {
94 SparseArray<E> clone = null;
95 try {
96 clone = (SparseArray<E>) super.clone();
97 clone.mKeys = mKeys.clone();
98 clone.mValues = mValues.clone();
99 } catch (CloneNotSupportedException cnse) {
100 /* ignore */
101 }
102 return clone;
103 }
104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 /**
106 * Gets the Object mapped from the specified key, or <code>null</code>
107 * if no such mapping has been made.
108 */
109 public E get(int key) {
110 return get(key, null);
111 }
112
113 /**
114 * Gets the Object mapped from the specified key, or the specified Object
115 * if no such mapping has been made.
116 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700117 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 public E get(int key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700119 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
121 if (i < 0 || mValues[i] == DELETED) {
122 return valueIfKeyNotFound;
123 } else {
124 return (E) mValues[i];
125 }
126 }
127
128 /**
129 * Removes the mapping from the specified key, if there was any.
130 */
131 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700132 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
134 if (i >= 0) {
135 if (mValues[i] != DELETED) {
136 mValues[i] = DELETED;
137 mGarbage = true;
138 }
139 }
140 }
141
142 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700143 * @hide
144 * Removes the mapping from the specified key, if there was any, returning the old value.
145 */
146 public E removeReturnOld(int key) {
147 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
148
149 if (i >= 0) {
150 if (mValues[i] != DELETED) {
151 final E old = (E) mValues[i];
152 mValues[i] = DELETED;
153 mGarbage = true;
154 return old;
155 }
156 }
157 return null;
158 }
159
160 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 * Alias for {@link #delete(int)}.
162 */
163 public void remove(int key) {
164 delete(key);
165 }
166
Dianne Hackbornc8017682010-07-06 13:34:38 -0700167 /**
168 * Removes the mapping at the specified index.
Phil Weaveradaafb22016-05-19 10:32:52 -0700169 *
170 * <p>For indices outside of the range <code>0...size()-1</code>,
171 * the behavior is undefined.</p>
Dianne Hackbornc8017682010-07-06 13:34:38 -0700172 */
173 public void removeAt(int index) {
174 if (mValues[index] != DELETED) {
175 mValues[index] = DELETED;
176 mGarbage = true;
177 }
178 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700179
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700180 /**
181 * Remove a range of mappings as a batch.
182 *
183 * @param index Index to begin at
184 * @param size Number of mappings to remove
Phil Weaveradaafb22016-05-19 10:32:52 -0700185 *
186 * <p>For indices outside of the range <code>0...size()-1</code>,
187 * the behavior is undefined.</p>
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700188 */
189 public void removeAtRange(int index, int size) {
190 final int end = Math.min(mSize, index + size);
191 for (int i = index; i < end; i++) {
192 removeAt(i);
193 }
194 }
195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private void gc() {
197 // Log.e("SparseArray", "gc start with " + mSize);
198
199 int n = mSize;
200 int o = 0;
201 int[] keys = mKeys;
202 Object[] values = mValues;
203
204 for (int i = 0; i < n; i++) {
205 Object val = values[i];
206
207 if (val != DELETED) {
208 if (i != o) {
209 keys[o] = keys[i];
210 values[o] = val;
Svetoslav Ganovd116d7c2011-11-21 18:41:59 -0800211 values[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 }
213
214 o++;
215 }
216 }
217
218 mGarbage = false;
219 mSize = o;
220
221 // Log.e("SparseArray", "gc end with " + mSize);
222 }
223
224 /**
225 * Adds a mapping from the specified key to the specified value,
226 * replacing the previous mapping from the specified key if there
227 * was one.
228 */
229 public void put(int key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700230 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 if (i >= 0) {
233 mValues[i] = value;
234 } else {
235 i = ~i;
236
237 if (i < mSize && mValues[i] == DELETED) {
238 mKeys[i] = key;
239 mValues[i] = value;
240 return;
241 }
242
243 if (mGarbage && mSize >= mKeys.length) {
244 gc();
245
246 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700247 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 }
249
Adam Lesinski776abc22014-03-07 11:30:59 -0500250 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
251 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mSize++;
253 }
254 }
255
256 /**
257 * Returns the number of key-value mappings that this SparseArray
258 * currently stores.
259 */
260 public int size() {
261 if (mGarbage) {
262 gc();
263 }
264
265 return mSize;
266 }
267
268 /**
269 * Given an index in the range <code>0...size()-1</code>, returns
270 * the key from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700271 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100272 *
273 * <p>The keys corresponding to indices in ascending order are guaranteed to
274 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
275 * smallest key and <code>keyAt(size()-1)</code> will return the largest
276 * key.</p>
Phil Weaveradaafb22016-05-19 10:32:52 -0700277 *
278 * <p>For indices outside of the range <code>0...size()-1</code>,
279 * the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 */
281 public int keyAt(int index) {
282 if (mGarbage) {
283 gc();
284 }
285
286 return mKeys[index];
287 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 /**
290 * Given an index in the range <code>0...size()-1</code>, returns
291 * the value from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700292 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100293 *
294 * <p>The values corresponding to indices in ascending order are guaranteed
295 * to be associated with keys in ascending order, e.g.,
296 * <code>valueAt(0)</code> will return the value associated with the
297 * smallest key and <code>valueAt(size()-1)</code> will return the value
298 * associated with the largest key.</p>
Phil Weaveradaafb22016-05-19 10:32:52 -0700299 *
300 * <p>For indices outside of the range <code>0...size()-1</code>,
301 * the behavior is undefined.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700303 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 public E valueAt(int index) {
305 if (mGarbage) {
306 gc();
307 }
308
309 return (E) mValues[index];
310 }
311
312 /**
313 * Given an index in the range <code>0...size()-1</code>, sets a new
314 * value for the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700315 * SparseArray stores.
Phil Weaveradaafb22016-05-19 10:32:52 -0700316 *
317 * <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 -0800318 */
319 public void setValueAt(int index, E value) {
320 if (mGarbage) {
321 gc();
322 }
323
324 mValues[index] = value;
325 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 /**
328 * Returns the index for which {@link #keyAt} would return the
329 * specified key, or a negative number if the specified
330 * key is not mapped.
331 */
332 public int indexOfKey(int key) {
333 if (mGarbage) {
334 gc();
335 }
336
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700337 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 }
339
340 /**
341 * Returns an index for which {@link #valueAt} would return the
Laura Davise27c3512018-07-26 15:21:45 -0700342 * specified value, or a negative number if no keys map to the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * specified value.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700344 * <p>Beware that this is a linear search, unlike lookups by key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 * and that multiple keys can map to the same value and this will
346 * find only one of them.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700347 * <p>Note also that unlike most collections' {@code indexOf} methods,
348 * this method compares values using {@code ==} rather than {@code equals}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 */
350 public int indexOfValue(E value) {
351 if (mGarbage) {
352 gc();
353 }
354
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700355 for (int i = 0; i < mSize; i++) {
356 if (mValues[i] == value) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 return i;
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700358 }
359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360
361 return -1;
362 }
363
364 /**
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700365 * Returns an index for which {@link #valueAt} would return the
Laura Davise27c3512018-07-26 15:21:45 -0700366 * specified value, or a negative number if no keys map to the
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700367 * specified value.
368 * <p>Beware that this is a linear search, unlike lookups by key,
369 * and that multiple keys can map to the same value and this will
370 * find only one of them.
371 * <p>Note also that this method uses {@code equals} unlike {@code indexOfValue}.
Suprabh Shukla0693ff62017-03-23 16:09:27 -0700372 * @hide
Tejas Khoranaf3b09b92016-07-13 14:00:09 -0700373 */
374 public int indexOfValueByValue(E value) {
375 if (mGarbage) {
376 gc();
377 }
378
379 for (int i = 0; i < mSize; i++) {
380 if (value == null) {
381 if (mValues[i] == null) {
382 return i;
383 }
384 } else {
385 if (value.equals(mValues[i])) {
386 return i;
387 }
388 }
389 }
390 return -1;
391 }
392
393 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 * Removes all key-value mappings from this SparseArray.
395 */
396 public void clear() {
397 int n = mSize;
398 Object[] values = mValues;
399
400 for (int i = 0; i < n; i++) {
401 values[i] = null;
402 }
403
404 mSize = 0;
405 mGarbage = false;
406 }
407
408 /**
409 * Puts a key/value pair into the array, optimizing for the case where
410 * the key is greater than all existing keys in the array.
411 */
412 public void append(int key, E value) {
413 if (mSize != 0 && key <= mKeys[mSize - 1]) {
414 put(key, value);
415 return;
416 }
417
418 if (mGarbage && mSize >= mKeys.length) {
419 gc();
420 }
421
Adam Lesinski776abc22014-03-07 11:30:59 -0500422 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
423 mValues = GrowingArrayUtils.append(mValues, mSize, value);
424 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700426
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700427 /**
428 * {@inheritDoc}
429 *
430 * <p>This implementation composes a string by iterating over its mappings. If
431 * this map contains itself as a value, the string "(this Map)"
432 * will appear in its place.
433 */
434 @Override
435 public String toString() {
436 if (size() <= 0) {
437 return "{}";
438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700440 StringBuilder buffer = new StringBuilder(mSize * 28);
441 buffer.append('{');
442 for (int i=0; i<mSize; i++) {
443 if (i > 0) {
444 buffer.append(", ");
445 }
446 int key = keyAt(i);
447 buffer.append(key);
448 buffer.append('=');
449 Object value = valueAt(i);
450 if (value != this) {
451 buffer.append(value);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700452 } else {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700453 buffer.append("(this Map)");
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700456 buffer.append('}');
457 return buffer.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459}