blob: 73e17a61d17f34b6b35680c4417524cdd8a7d8bd [file] [log] [blame]
Romain Guyfdbf6a72009-06-18 15:13:40 -07001/*
2 * Copyright (C) 2009 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
Philip P. Moltmann59076d82019-08-19 15:00:40 -070019import android.os.Parcel;
Philip P. Moltmann59076d82019-08-19 15:00:40 -070020
Romain Guyfdbf6a72009-06-18 15:13:40 -070021import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050022import com.android.internal.util.GrowingArrayUtils;
Philip P. Moltmann59076d82019-08-19 15:00:40 -070023import com.android.internal.util.Preconditions;
Adam Lesinski776abc22014-03-07 11:30:59 -050024
25import libcore.util.EmptyArray;
Romain Guyfdbf6a72009-06-18 15:13:40 -070026
Philip P. Moltmannbadc09c2019-10-23 10:28:27 -070027import java.util.Arrays;
28
Romain Guyfdbf6a72009-06-18 15:13:40 -070029/**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080030 * SparseArray mapping longs to Objects. Unlike a normal array of Objects,
Dianne Hackbornb993f412013-07-12 17:46:45 -070031 * there can be gaps in the indices. It is intended to be more memory efficient
32 * than using a HashMap to map Longs to Objects, both because it avoids
33 * auto-boxing keys and its data structure doesn't rely on an extra entry object
34 * for each mapping.
35 *
36 * <p>Note that this container keeps its mappings in an array data structure,
37 * using a binary search to find keys. The implementation is not intended to be appropriate for
38 * data structures
39 * that may contain large numbers of items. It is generally slower than a traditional
40 * HashMap, since lookups require a binary search and adds and removes require inserting
41 * and deleting entries in the array. For containers holding up to hundreds of items,
42 * the performance difference is not significant, less than 50%.</p>
43 *
44 * <p>To help with performance, the container includes an optimization when removing
45 * keys: instead of compacting its array immediately, it leaves the removed entry marked
46 * as deleted. The entry can then be re-used for the same key, or compacted later in
47 * a single garbage collection step of all removed entries. This garbage collection will
48 * need to be performed at any time the array needs to be grown or the the map size or
49 * entry values are retrieved.</p>
Flavio Lerda57713022013-09-08 18:04:58 +010050 *
51 * <p>It is possible to iterate over the items in this container using
52 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
53 * <code>keyAt(int)</code> with ascending values of the index will return the
54 * keys in ascending order, or the values corresponding to the keys in ascending
Newton Allenebb47952013-11-21 13:27:10 -080055 * order in the case of <code>valueAt(int)</code>.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -070056 */
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080057public class LongSparseArray<E> implements Cloneable {
Romain Guyfdbf6a72009-06-18 15:13:40 -070058 private static final Object DELETED = new Object();
59 private boolean mGarbage = false;
60
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080061 private long[] mKeys;
62 private Object[] mValues;
63 private int mSize;
64
Romain Guyfdbf6a72009-06-18 15:13:40 -070065 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080066 * Creates a new LongSparseArray containing no mappings.
Romain Guyfdbf6a72009-06-18 15:13:40 -070067 */
68 public LongSparseArray() {
69 this(10);
70 }
71
72 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080073 * Creates a new LongSparseArray containing no mappings that will not
Romain Guyfdbf6a72009-06-18 15:13:40 -070074 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070075 * number of mappings. If you supply an initial capacity of 0, the
76 * sparse array will be initialized with a light-weight representation
77 * not requiring any additional array allocations.
Romain Guyfdbf6a72009-06-18 15:13:40 -070078 */
79 public LongSparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070080 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050081 mKeys = EmptyArray.LONG;
82 mValues = EmptyArray.OBJECT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070083 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050084 mKeys = ArrayUtils.newUnpaddedLongArray(initialCapacity);
85 mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070086 }
Romain Guyfdbf6a72009-06-18 15:13:40 -070087 mSize = 0;
88 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080089
90 @Override
91 @SuppressWarnings("unchecked")
92 public LongSparseArray<E> clone() {
93 LongSparseArray<E> clone = null;
94 try {
95 clone = (LongSparseArray<E>) super.clone();
96 clone.mKeys = mKeys.clone();
97 clone.mValues = mValues.clone();
98 } catch (CloneNotSupportedException cnse) {
99 /* ignore */
Adam Powell8f1bfe12010-03-05 15:13:56 -0800100 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800101 return clone;
Adam Powell8f1bfe12010-03-05 15:13:56 -0800102 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700103
104 /**
105 * Gets the Object mapped from the specified key, or <code>null</code>
106 * if no such mapping has been made.
107 */
108 public E get(long key) {
109 return get(key, null);
110 }
111
112 /**
113 * Gets the Object mapped from the specified key, or the specified Object
114 * if no such mapping has been made.
115 */
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800116 @SuppressWarnings("unchecked")
Romain Guyfdbf6a72009-06-18 15:13:40 -0700117 public E get(long key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700118 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700119
120 if (i < 0 || mValues[i] == DELETED) {
121 return valueIfKeyNotFound;
122 } else {
123 return (E) mValues[i];
124 }
125 }
126
127 /**
128 * Removes the mapping from the specified key, if there was any.
129 */
130 public void delete(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700131 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700132
133 if (i >= 0) {
134 if (mValues[i] != DELETED) {
135 mValues[i] = DELETED;
136 mGarbage = true;
137 }
138 }
139 }
140
141 /**
142 * Alias for {@link #delete(long)}.
143 */
144 public void remove(long key) {
145 delete(key);
146 }
147
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800148 /**
149 * Removes the mapping at the specified index.
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700150 *
151 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
152 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
153 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
154 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800155 */
156 public void removeAt(int index) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700157 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000158 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700159 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000160 throw new ArrayIndexOutOfBoundsException(index);
161 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800162 if (mValues[index] != DELETED) {
163 mValues[index] = DELETED;
164 mGarbage = true;
165 }
166 }
167
Romain Guyfdbf6a72009-06-18 15:13:40 -0700168 private void gc() {
169 // Log.e("SparseArray", "gc start with " + mSize);
170
171 int n = mSize;
172 int o = 0;
173 long[] keys = mKeys;
174 Object[] values = mValues;
175
176 for (int i = 0; i < n; i++) {
177 Object val = values[i];
178
179 if (val != DELETED) {
180 if (i != o) {
181 keys[o] = keys[i];
182 values[o] = val;
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800183 values[i] = null;
Romain Guyfdbf6a72009-06-18 15:13:40 -0700184 }
185
186 o++;
187 }
188 }
189
190 mGarbage = false;
191 mSize = o;
192
193 // Log.e("SparseArray", "gc end with " + mSize);
194 }
195
196 /**
197 * Adds a mapping from the specified key to the specified value,
198 * replacing the previous mapping from the specified key if there
199 * was one.
200 */
201 public void put(long key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700202 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700203
204 if (i >= 0) {
205 mValues[i] = value;
206 } else {
207 i = ~i;
208
209 if (i < mSize && mValues[i] == DELETED) {
210 mKeys[i] = key;
211 mValues[i] = value;
212 return;
213 }
214
215 if (mGarbage && mSize >= mKeys.length) {
216 gc();
217
218 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700219 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700220 }
221
Adam Lesinski776abc22014-03-07 11:30:59 -0500222 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
223 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700224 mSize++;
225 }
226 }
227
228 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800229 * Returns the number of key-value mappings that this LongSparseArray
Romain Guyfdbf6a72009-06-18 15:13:40 -0700230 * currently stores.
231 */
232 public int size() {
233 if (mGarbage) {
234 gc();
235 }
236
237 return mSize;
238 }
239
240 /**
241 * Given an index in the range <code>0...size()-1</code>, returns
242 * the key from the <code>index</code>th key-value mapping that this
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800243 * LongSparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100244 *
245 * <p>The keys corresponding to indices in ascending order are guaranteed to
246 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
247 * smallest key and <code>keyAt(size()-1)</code> will return the largest
248 * key.</p>
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700249 *
250 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
251 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
252 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
253 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -0700254 */
255 public long keyAt(int index) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700256 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000257 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700258 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000259 throw new ArrayIndexOutOfBoundsException(index);
260 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700261 if (mGarbage) {
262 gc();
263 }
264
265 return mKeys[index];
266 }
267
268 /**
269 * Given an index in the range <code>0...size()-1</code>, returns
270 * the value from the <code>index</code>th key-value mapping that this
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800271 * LongSparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100272 *
273 * <p>The values corresponding to indices in ascending order are guaranteed
274 * to be associated with keys in ascending order, e.g.,
275 * <code>valueAt(0)</code> will return the value associated with the
276 * smallest key and <code>valueAt(size()-1)</code> will return the value
277 * associated with the largest key.</p>
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700278 *
279 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
280 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
281 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
282 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -0700283 */
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800284 @SuppressWarnings("unchecked")
Romain Guyfdbf6a72009-06-18 15:13:40 -0700285 public E valueAt(int index) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700286 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000287 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700288 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000289 throw new ArrayIndexOutOfBoundsException(index);
290 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700291 if (mGarbage) {
292 gc();
293 }
294
295 return (E) mValues[index];
296 }
297
298 /**
299 * Given an index in the range <code>0...size()-1</code>, sets a new
300 * value for the <code>index</code>th key-value mapping that this
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800301 * LongSparseArray stores.
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700302 *
303 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
304 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
305 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
306 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -0700307 */
308 public void setValueAt(int index, E value) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700309 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000310 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700311 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000312 throw new ArrayIndexOutOfBoundsException(index);
313 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700314 if (mGarbage) {
315 gc();
316 }
317
318 mValues[index] = value;
319 }
320
321 /**
322 * Returns the index for which {@link #keyAt} would return the
323 * specified key, or a negative number if the specified
324 * key is not mapped.
325 */
326 public int indexOfKey(long key) {
327 if (mGarbage) {
328 gc();
329 }
330
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700331 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700332 }
333
334 /**
335 * Returns an index for which {@link #valueAt} would return the
336 * specified key, or a negative number if no keys map to the
337 * specified value.
338 * Beware that this is a linear search, unlike lookups by key,
339 * and that multiple keys can map to the same value and this will
340 * find only one of them.
341 */
342 public int indexOfValue(E value) {
343 if (mGarbage) {
344 gc();
345 }
346
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700347 for (int i = 0; i < mSize; i++) {
348 if (mValues[i] == value) {
Romain Guyfdbf6a72009-06-18 15:13:40 -0700349 return i;
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700350 }
351 }
352 return -1;
353 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700354
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700355 /**
356 * Returns an index for which {@link #valueAt} would return the
357 * specified key, or a negative number if no keys map to the
358 * specified value.
359 * <p>Beware that this is a linear search, unlike lookups by key,
360 * and that multiple keys can map to the same value and this will
361 * find only one of them.
362 * <p>Note also that this method uses {@code equals} unlike {@code indexOfValue}.
Suprabh Shukla0693ff62017-03-23 16:09:27 -0700363 * @hide
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700364 */
365 public int indexOfValueByValue(E value) {
366 if (mGarbage) {
367 gc();
368 }
369
370 for (int i = 0; i < mSize; i++) {
371 if (value == null) {
372 if (mValues[i] == null) {
373 return i;
374 }
375 } else {
376 if (value.equals(mValues[i])) {
377 return i;
378 }
379 }
380 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700381 return -1;
382 }
383
384 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800385 * Removes all key-value mappings from this LongSparseArray.
Romain Guyfdbf6a72009-06-18 15:13:40 -0700386 */
387 public void clear() {
388 int n = mSize;
389 Object[] values = mValues;
390
391 for (int i = 0; i < n; i++) {
392 values[i] = null;
393 }
394
395 mSize = 0;
396 mGarbage = false;
397 }
398
399 /**
400 * Puts a key/value pair into the array, optimizing for the case where
401 * the key is greater than all existing keys in the array.
402 */
403 public void append(long key, E value) {
404 if (mSize != 0 && key <= mKeys[mSize - 1]) {
405 put(key, value);
406 return;
407 }
408
409 if (mGarbage && mSize >= mKeys.length) {
410 gc();
411 }
412
Adam Lesinski776abc22014-03-07 11:30:59 -0500413 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
414 mValues = GrowingArrayUtils.append(mValues, mSize, value);
415 mSize++;
Romain Guyfdbf6a72009-06-18 15:13:40 -0700416 }
417
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700418 /**
419 * {@inheritDoc}
420 *
421 * <p>This implementation composes a string by iterating over its mappings. If
422 * this map contains itself as a value, the string "(this Map)"
423 * will appear in its place.
424 */
425 @Override
426 public String toString() {
427 if (size() <= 0) {
428 return "{}";
Romain Guyfdbf6a72009-06-18 15:13:40 -0700429 }
430
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700431 StringBuilder buffer = new StringBuilder(mSize * 28);
432 buffer.append('{');
433 for (int i=0; i<mSize; i++) {
434 if (i > 0) {
435 buffer.append(", ");
436 }
437 long key = keyAt(i);
438 buffer.append(key);
439 buffer.append('=');
440 Object value = valueAt(i);
441 if (value != this) {
442 buffer.append(value);
443 } else {
444 buffer.append("(this Map)");
445 }
446 }
447 buffer.append('}');
448 return buffer.toString();
Romain Guyfdbf6a72009-06-18 15:13:40 -0700449 }
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700450
451 /**
452 * @hide
453 */
Philip P. Moltmannbadc09c2019-10-23 10:28:27 -0700454 public static class StringParcelling implements
455 com.android.internal.util.Parcelling<LongSparseArray<String>> {
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700456 @Override
Philip P. Moltmannbadc09c2019-10-23 10:28:27 -0700457 public void parcel(LongSparseArray<String> array, Parcel dest, int parcelFlags) {
458 if (array == null) {
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700459 dest.writeInt(-1);
460 return;
461 }
462
Philip P. Moltmannbadc09c2019-10-23 10:28:27 -0700463 int size = array.mSize;
464
465 dest.writeInt(size);
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700466 dest.writeLongArray(array.mKeys);
Philip P. Moltmannbadc09c2019-10-23 10:28:27 -0700467
468 dest.writeStringArray(Arrays.copyOfRange(array.mValues, 0, size, String[].class));
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700469 }
470
471 @Override
Philip P. Moltmannbadc09c2019-10-23 10:28:27 -0700472 public LongSparseArray<String> unparcel(Parcel source) {
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700473 int size = source.readInt();
474 if (size == -1) {
475 return null;
476 }
477
478 LongSparseArray<String> array = new LongSparseArray<>(0);
479 array.mSize = size;
480 array.mKeys = source.createLongArray();
481 array.mValues = source.createStringArray();
482
483 // Make sure array is sane
484 Preconditions.checkArgument(array.mKeys.length >= size);
485 Preconditions.checkArgument(array.mValues.length >= size);
486
487 if (size > 0) {
488 long last = array.mKeys[0];
489 for (int i = 1; i < size; i++) {
490 Preconditions.checkArgument(last < array.mKeys[i]);
491 }
492 }
493
494 return array;
495 }
496 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800497}