blob: dc965edd7fada867db9273bb14a126e985ddd5a9 [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/**
25 * SparseArrays map integers 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 Integers 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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070052public class SparseArray<E> implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 private static final Object DELETED = new Object();
54 private boolean mGarbage = false;
55
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070056 private int[] mKeys;
57 private Object[] mValues;
58 private int mSize;
59
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 /**
61 * Creates a new SparseArray containing no mappings.
62 */
63 public SparseArray() {
64 this(10);
65 }
66
67 /**
68 * Creates a new SparseArray containing no mappings that will not
69 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 */
74 public SparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070075 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050076 mKeys = EmptyArray.INT;
77 mValues = EmptyArray.OBJECT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070078 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050079 mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
80 mKeys = new int[mValues.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 mSize = 0;
83 }
84
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070085 @Override
86 @SuppressWarnings("unchecked")
87 public SparseArray<E> clone() {
88 SparseArray<E> clone = null;
89 try {
90 clone = (SparseArray<E>) super.clone();
91 clone.mKeys = mKeys.clone();
92 clone.mValues = mValues.clone();
93 } catch (CloneNotSupportedException cnse) {
94 /* ignore */
95 }
96 return clone;
97 }
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 /**
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(int 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 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700111 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 public E get(int key, E valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700113 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
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(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700126 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
128 if (i >= 0) {
129 if (mValues[i] != DELETED) {
130 mValues[i] = DELETED;
131 mGarbage = true;
132 }
133 }
134 }
135
136 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700137 * @hide
138 * Removes the mapping from the specified key, if there was any, returning the old value.
139 */
140 public E removeReturnOld(int key) {
141 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
142
143 if (i >= 0) {
144 if (mValues[i] != DELETED) {
145 final E old = (E) mValues[i];
146 mValues[i] = DELETED;
147 mGarbage = true;
148 return old;
149 }
150 }
151 return null;
152 }
153
154 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 * Alias for {@link #delete(int)}.
156 */
157 public void remove(int key) {
158 delete(key);
159 }
160
Dianne Hackbornc8017682010-07-06 13:34:38 -0700161 /**
162 * Removes the mapping at the specified index.
163 */
164 public void removeAt(int index) {
165 if (mValues[index] != DELETED) {
166 mValues[index] = DELETED;
167 mGarbage = true;
168 }
169 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700170
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700171 /**
172 * Remove a range of mappings as a batch.
173 *
174 * @param index Index to begin at
175 * @param size Number of mappings to remove
176 */
177 public void removeAtRange(int index, int size) {
178 final int end = Math.min(mSize, index + size);
179 for (int i = index; i < end; i++) {
180 removeAt(i);
181 }
182 }
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 private void gc() {
185 // Log.e("SparseArray", "gc start with " + mSize);
186
187 int n = mSize;
188 int o = 0;
189 int[] keys = mKeys;
190 Object[] values = mValues;
191
192 for (int i = 0; i < n; i++) {
193 Object val = values[i];
194
195 if (val != DELETED) {
196 if (i != o) {
197 keys[o] = keys[i];
198 values[o] = val;
Svetoslav Ganovd116d7c2011-11-21 18:41:59 -0800199 values[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 }
201
202 o++;
203 }
204 }
205
206 mGarbage = false;
207 mSize = o;
208
209 // Log.e("SparseArray", "gc end with " + mSize);
210 }
211
212 /**
213 * Adds a mapping from the specified key to the specified value,
214 * replacing the previous mapping from the specified key if there
215 * was one.
216 */
217 public void put(int key, E value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700218 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
220 if (i >= 0) {
221 mValues[i] = value;
222 } else {
223 i = ~i;
224
225 if (i < mSize && mValues[i] == DELETED) {
226 mKeys[i] = key;
227 mValues[i] = value;
228 return;
229 }
230
231 if (mGarbage && mSize >= mKeys.length) {
232 gc();
233
234 // Search again because indices may have changed.
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700235 i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 }
237
Adam Lesinski776abc22014-03-07 11:30:59 -0500238 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
239 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 mSize++;
241 }
242 }
243
244 /**
245 * Returns the number of key-value mappings that this SparseArray
246 * currently stores.
247 */
248 public int size() {
249 if (mGarbage) {
250 gc();
251 }
252
253 return mSize;
254 }
255
256 /**
257 * Given an index in the range <code>0...size()-1</code>, returns
258 * the key from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700259 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100260 *
261 * <p>The keys corresponding to indices in ascending order are guaranteed to
262 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
263 * smallest key and <code>keyAt(size()-1)</code> will return the largest
264 * key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 */
266 public int keyAt(int index) {
267 if (mGarbage) {
268 gc();
269 }
270
271 return mKeys[index];
272 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 /**
275 * Given an index in the range <code>0...size()-1</code>, returns
276 * the value from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700277 * SparseArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100278 *
279 * <p>The values corresponding to indices in ascending order are guaranteed
280 * to be associated with keys in ascending order, e.g.,
281 * <code>valueAt(0)</code> will return the value associated with the
282 * smallest key and <code>valueAt(size()-1)</code> will return the value
283 * associated with the largest key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700285 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 public E valueAt(int index) {
287 if (mGarbage) {
288 gc();
289 }
290
291 return (E) mValues[index];
292 }
293
294 /**
295 * Given an index in the range <code>0...size()-1</code>, sets a new
296 * value for the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700297 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 */
299 public void setValueAt(int index, E value) {
300 if (mGarbage) {
301 gc();
302 }
303
304 mValues[index] = value;
305 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 /**
308 * Returns the index for which {@link #keyAt} would return the
309 * specified key, or a negative number if the specified
310 * key is not mapped.
311 */
312 public int indexOfKey(int key) {
313 if (mGarbage) {
314 gc();
315 }
316
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700317 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319
320 /**
321 * Returns an index for which {@link #valueAt} would return the
322 * specified key, or a negative number if no keys map to the
323 * specified value.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700324 * <p>Beware that this is a linear search, unlike lookups by key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 * and that multiple keys can map to the same value and this will
326 * find only one of them.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700327 * <p>Note also that unlike most collections' {@code indexOf} methods,
328 * this method compares values using {@code ==} rather than {@code equals}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 */
330 public int indexOfValue(E value) {
331 if (mGarbage) {
332 gc();
333 }
334
335 for (int i = 0; i < mSize; i++)
336 if (mValues[i] == value)
337 return i;
338
339 return -1;
340 }
341
342 /**
343 * Removes all key-value mappings from this SparseArray.
344 */
345 public void clear() {
346 int n = mSize;
347 Object[] values = mValues;
348
349 for (int i = 0; i < n; i++) {
350 values[i] = null;
351 }
352
353 mSize = 0;
354 mGarbage = false;
355 }
356
357 /**
358 * Puts a key/value pair into the array, optimizing for the case where
359 * the key is greater than all existing keys in the array.
360 */
361 public void append(int key, E value) {
362 if (mSize != 0 && key <= mKeys[mSize - 1]) {
363 put(key, value);
364 return;
365 }
366
367 if (mGarbage && mSize >= mKeys.length) {
368 gc();
369 }
370
Adam Lesinski776abc22014-03-07 11:30:59 -0500371 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
372 mValues = GrowingArrayUtils.append(mValues, mSize, value);
373 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700375
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700376 /**
377 * {@inheritDoc}
378 *
379 * <p>This implementation composes a string by iterating over its mappings. If
380 * this map contains itself as a value, the string "(this Map)"
381 * will appear in its place.
382 */
383 @Override
384 public String toString() {
385 if (size() <= 0) {
386 return "{}";
387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700389 StringBuilder buffer = new StringBuilder(mSize * 28);
390 buffer.append('{');
391 for (int i=0; i<mSize; i++) {
392 if (i > 0) {
393 buffer.append(", ");
394 }
395 int key = keyAt(i);
396 buffer.append(key);
397 buffer.append('=');
398 Object value = valueAt(i);
399 if (value != this) {
400 buffer.append(value);
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700401 } else {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700402 buffer.append("(this Map)");
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700405 buffer.append('}');
406 return buffer.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408}