blob: e4de7045721b9a35f803881f96b3d6ef124bd83b [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
19import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050020import com.android.internal.util.GrowingArrayUtils;
21
22import libcore.util.EmptyArray;
Romain Guyfdbf6a72009-06-18 15:13:40 -070023
24/**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080025 * SparseArray mapping longs to Objects. Unlike a normal array of Objects,
Dianne Hackbornb993f412013-07-12 17:46:45 -070026 * there can be gaps in the indices. It is intended to be more memory efficient
27 * than using a HashMap to map Longs to Objects, both because it avoids
28 * auto-boxing keys and its data structure doesn't rely on an extra entry object
29 * for each mapping.
30 *
31 * <p>Note that this container keeps its mappings in an array data structure,
32 * using a binary search to find keys. The implementation is not intended to be appropriate for
33 * data structures
34 * that may contain large numbers of items. It is generally slower than a traditional
35 * HashMap, since lookups require a binary search and adds and removes require inserting
36 * and deleting entries in the array. For containers holding up to hundreds of items,
37 * the performance difference is not significant, less than 50%.</p>
38 *
39 * <p>To help with performance, the container includes an optimization when removing
40 * keys: instead of compacting its array immediately, it leaves the removed entry marked
41 * as deleted. The entry can then be re-used for the same key, or compacted later in
42 * a single garbage collection step of all removed entries. This garbage collection will
43 * need to be performed at any time the array needs to be grown or the the map size or
44 * entry values are retrieved.</p>
Flavio Lerda57713022013-09-08 18:04:58 +010045 *
46 * <p>It is possible to iterate over the items in this container using
47 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
48 * <code>keyAt(int)</code> with ascending values of the index will return the
49 * keys in ascending order, or the values corresponding to the keys in ascending
Newton Allenebb47952013-11-21 13:27:10 -080050 * order in the case of <code>valueAt(int)</code>.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -070051 */
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080052public class LongSparseArray<E> implements Cloneable {
Romain Guyfdbf6a72009-06-18 15:13:40 -070053 private static final Object DELETED = new Object();
54 private boolean mGarbage = false;
55
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080056 private long[] mKeys;
57 private Object[] mValues;
58 private int mSize;
59
Romain Guyfdbf6a72009-06-18 15:13:40 -070060 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080061 * Creates a new LongSparseArray containing no mappings.
Romain Guyfdbf6a72009-06-18 15:13:40 -070062 */
63 public LongSparseArray() {
64 this(10);
65 }
66
67 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080068 * Creates a new LongSparseArray containing no mappings that will not
Romain Guyfdbf6a72009-06-18 15:13:40 -070069 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070070 * number of mappings. If you supply an initial capacity of 0, the
71 * sparse array will be initialized with a light-weight representation
72 * not requiring any additional array allocations.
Romain Guyfdbf6a72009-06-18 15:13:40 -070073 */
74 public LongSparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070075 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050076 mKeys = EmptyArray.LONG;
77 mValues = EmptyArray.OBJECT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070078 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050079 mKeys = ArrayUtils.newUnpaddedLongArray(initialCapacity);
80 mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070081 }
Romain Guyfdbf6a72009-06-18 15:13:40 -070082 mSize = 0;
83 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080084
85 @Override
86 @SuppressWarnings("unchecked")
87 public LongSparseArray<E> clone() {
88 LongSparseArray<E> clone = null;
89 try {
90 clone = (LongSparseArray<E>) super.clone();
91 clone.mKeys = mKeys.clone();
92 clone.mValues = mValues.clone();
93 } catch (CloneNotSupportedException cnse) {
94 /* ignore */
Adam Powell8f1bfe12010-03-05 15:13:56 -080095 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -080096 return clone;
Adam Powell8f1bfe12010-03-05 15:13:56 -080097 }
Romain Guyfdbf6a72009-06-18 15:13:40 -070098
99 /**
100 * Gets the Object mapped from the specified key, or <code>null</code>
101 * if no such mapping has been made.
102 */
103 public E get(long key) {
104 return get(key, null);
105 }
106
107 /**
108 * Gets the Object mapped from the specified key, or the specified Object
109 * if no such mapping has been made.
110 */
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800111 @SuppressWarnings("unchecked")
Romain Guyfdbf6a72009-06-18 15:13:40 -0700112 public E get(long key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700113 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700114
115 if (i < 0 || mValues[i] == DELETED) {
116 return valueIfKeyNotFound;
117 } else {
118 return (E) mValues[i];
119 }
120 }
121
122 /**
123 * Removes the mapping from the specified key, if there was any.
124 */
125 public void delete(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700126 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700127
128 if (i >= 0) {
129 if (mValues[i] != DELETED) {
130 mValues[i] = DELETED;
131 mGarbage = true;
132 }
133 }
134 }
135
136 /**
137 * Alias for {@link #delete(long)}.
138 */
139 public void remove(long key) {
140 delete(key);
141 }
142
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800143 /**
144 * Removes the mapping at the specified index.
145 */
146 public void removeAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800147 if (index >= mSize) {
148 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
149 throw new ArrayIndexOutOfBoundsException(index);
150 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800151 if (mValues[index] != DELETED) {
152 mValues[index] = DELETED;
153 mGarbage = true;
154 }
155 }
156
Romain Guyfdbf6a72009-06-18 15:13:40 -0700157 private void gc() {
158 // Log.e("SparseArray", "gc start with " + mSize);
159
160 int n = mSize;
161 int o = 0;
162 long[] keys = mKeys;
163 Object[] values = mValues;
164
165 for (int i = 0; i < n; i++) {
166 Object val = values[i];
167
168 if (val != DELETED) {
169 if (i != o) {
170 keys[o] = keys[i];
171 values[o] = val;
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800172 values[i] = null;
Romain Guyfdbf6a72009-06-18 15:13:40 -0700173 }
174
175 o++;
176 }
177 }
178
179 mGarbage = false;
180 mSize = o;
181
182 // Log.e("SparseArray", "gc end with " + mSize);
183 }
184
185 /**
186 * Adds a mapping from the specified key to the specified value,
187 * replacing the previous mapping from the specified key if there
188 * was one.
189 */
190 public void put(long key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700191 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700192
193 if (i >= 0) {
194 mValues[i] = value;
195 } else {
196 i = ~i;
197
198 if (i < mSize && mValues[i] == DELETED) {
199 mKeys[i] = key;
200 mValues[i] = value;
201 return;
202 }
203
204 if (mGarbage && mSize >= mKeys.length) {
205 gc();
206
207 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700208 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700209 }
210
Adam Lesinski776abc22014-03-07 11:30:59 -0500211 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
212 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700213 mSize++;
214 }
215 }
216
217 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800218 * Returns the number of key-value mappings that this LongSparseArray
Romain Guyfdbf6a72009-06-18 15:13:40 -0700219 * currently stores.
220 */
221 public int size() {
222 if (mGarbage) {
223 gc();
224 }
225
226 return mSize;
227 }
228
229 /**
230 * Given an index in the range <code>0...size()-1</code>, returns
231 * the key from the <code>index</code>th key-value mapping that this
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800232 * LongSparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100233 *
234 * <p>The keys corresponding to indices in ascending order are guaranteed to
235 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
236 * smallest key and <code>keyAt(size()-1)</code> will return the largest
237 * key.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -0700238 */
239 public long keyAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800240 if (index >= mSize) {
241 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
242 throw new ArrayIndexOutOfBoundsException(index);
243 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700244 if (mGarbage) {
245 gc();
246 }
247
248 return mKeys[index];
249 }
250
251 /**
252 * Given an index in the range <code>0...size()-1</code>, returns
253 * the value from the <code>index</code>th key-value mapping that this
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800254 * LongSparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100255 *
256 * <p>The values corresponding to indices in ascending order are guaranteed
257 * to be associated with keys in ascending order, e.g.,
258 * <code>valueAt(0)</code> will return the value associated with the
259 * smallest key and <code>valueAt(size()-1)</code> will return the value
260 * associated with the largest key.</p>
Romain Guyfdbf6a72009-06-18 15:13:40 -0700261 */
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800262 @SuppressWarnings("unchecked")
Romain Guyfdbf6a72009-06-18 15:13:40 -0700263 public E valueAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800264 if (index >= mSize) {
265 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
266 throw new ArrayIndexOutOfBoundsException(index);
267 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700268 if (mGarbage) {
269 gc();
270 }
271
272 return (E) mValues[index];
273 }
274
275 /**
276 * Given an index in the range <code>0...size()-1</code>, sets a new
277 * value for the <code>index</code>th key-value mapping that this
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800278 * LongSparseArray stores.
Romain Guyfdbf6a72009-06-18 15:13:40 -0700279 */
280 public void setValueAt(int index, E value) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800281 if (index >= mSize) {
282 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
283 throw new ArrayIndexOutOfBoundsException(index);
284 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700285 if (mGarbage) {
286 gc();
287 }
288
289 mValues[index] = value;
290 }
291
292 /**
293 * Returns the index for which {@link #keyAt} would return the
294 * specified key, or a negative number if the specified
295 * key is not mapped.
296 */
297 public int indexOfKey(long key) {
298 if (mGarbage) {
299 gc();
300 }
301
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700302 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Romain Guyfdbf6a72009-06-18 15:13:40 -0700303 }
304
305 /**
306 * Returns an index for which {@link #valueAt} would return the
307 * specified key, or a negative number if no keys map to the
308 * specified value.
309 * Beware that this is a linear search, unlike lookups by key,
310 * and that multiple keys can map to the same value and this will
311 * find only one of them.
312 */
313 public int indexOfValue(E value) {
314 if (mGarbage) {
315 gc();
316 }
317
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700318 for (int i = 0; i < mSize; i++) {
319 if (mValues[i] == value) {
Romain Guyfdbf6a72009-06-18 15:13:40 -0700320 return i;
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700321 }
322 }
323 return -1;
324 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700325
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700326 /**
327 * Returns an index for which {@link #valueAt} would return the
328 * specified key, or a negative number if no keys map to the
329 * specified value.
330 * <p>Beware that this is a linear search, unlike lookups by key,
331 * and that multiple keys can map to the same value and this will
332 * find only one of them.
333 * <p>Note also that this method uses {@code equals} unlike {@code indexOfValue}.
Suprabh Shukla0693ff62017-03-23 16:09:27 -0700334 * @hide
Tejas Khoranafb5166d2016-07-18 11:18:27 -0700335 */
336 public int indexOfValueByValue(E value) {
337 if (mGarbage) {
338 gc();
339 }
340
341 for (int i = 0; i < mSize; i++) {
342 if (value == null) {
343 if (mValues[i] == null) {
344 return i;
345 }
346 } else {
347 if (value.equals(mValues[i])) {
348 return i;
349 }
350 }
351 }
Romain Guyfdbf6a72009-06-18 15:13:40 -0700352 return -1;
353 }
354
355 /**
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800356 * Removes all key-value mappings from this LongSparseArray.
Romain Guyfdbf6a72009-06-18 15:13:40 -0700357 */
358 public void clear() {
359 int n = mSize;
360 Object[] values = mValues;
361
362 for (int i = 0; i < n; i++) {
363 values[i] = null;
364 }
365
366 mSize = 0;
367 mGarbage = false;
368 }
369
370 /**
371 * Puts a key/value pair into the array, optimizing for the case where
372 * the key is greater than all existing keys in the array.
373 */
374 public void append(long key, E value) {
375 if (mSize != 0 && key <= mKeys[mSize - 1]) {
376 put(key, value);
377 return;
378 }
379
380 if (mGarbage && mSize >= mKeys.length) {
381 gc();
382 }
383
Adam Lesinski776abc22014-03-07 11:30:59 -0500384 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
385 mValues = GrowingArrayUtils.append(mValues, mSize, value);
386 mSize++;
Romain Guyfdbf6a72009-06-18 15:13:40 -0700387 }
388
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700389 /**
390 * {@inheritDoc}
391 *
392 * <p>This implementation composes a string by iterating over its mappings. If
393 * this map contains itself as a value, the string "(this Map)"
394 * will appear in its place.
395 */
396 @Override
397 public String toString() {
398 if (size() <= 0) {
399 return "{}";
Romain Guyfdbf6a72009-06-18 15:13:40 -0700400 }
401
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700402 StringBuilder buffer = new StringBuilder(mSize * 28);
403 buffer.append('{');
404 for (int i=0; i<mSize; i++) {
405 if (i > 0) {
406 buffer.append(", ");
407 }
408 long key = keyAt(i);
409 buffer.append(key);
410 buffer.append('=');
411 Object value = valueAt(i);
412 if (value != this) {
413 buffer.append(value);
414 } else {
415 buffer.append("(this Map)");
416 }
417 }
418 buffer.append('}');
419 return buffer.toString();
Romain Guyfdbf6a72009-06-18 15:13:40 -0700420 }
Dianne Hackborn9c1d2982012-02-10 12:36:18 -0800421}