blob: 0e013c376303a1060e4fc5c782010b18b28d60ad [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;
20
21/**
22 * SparseArrays map integers to Objects. Unlike a normal array of Objects,
Dianne Hackbornb993f412013-07-12 17:46:45 -070023 * there can be gaps in the indices. It is intended to be more memory efficient
24 * than using a HashMap to map Integers to Objects, both because it avoids
25 * auto-boxing keys and its data structure doesn't rely on an extra entry object
26 * for each mapping.
27 *
28 * <p>Note that this container keeps its mappings in an array data structure,
29 * using a binary search to find keys. The implementation is not intended to be appropriate for
30 * data structures
31 * that may contain large numbers of items. It is generally slower than a traditional
32 * HashMap, since lookups require a binary search and adds and removes require inserting
33 * and deleting entries in the array. For containers holding up to hundreds of items,
34 * the performance difference is not significant, less than 50%.</p>
35 *
36 * <p>To help with performance, the container includes an optimization when removing
37 * keys: instead of compacting its array immediately, it leaves the removed entry marked
38 * as deleted. The entry can then be re-used for the same key, or compacted later in
39 * a single garbage collection step of all removed entries. This garbage collection will
40 * need to be performed at any time the array needs to be grown or the the map size or
41 * entry values are retrieved.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070043public class SparseArray<E> implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 private static final Object DELETED = new Object();
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070045 static final int[] EMPTY_INTS = new int[0];
46 static final Object[] EMPTY_OBJECTS = new Object[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 private boolean mGarbage = false;
48
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070049 private int[] mKeys;
50 private Object[] mValues;
51 private int mSize;
52
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 /**
54 * Creates a new SparseArray containing no mappings.
55 */
56 public SparseArray() {
57 this(10);
58 }
59
60 /**
61 * Creates a new SparseArray containing no mappings that will not
62 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070063 * number of mappings. If you supply an initial capacity of 0, the
64 * sparse array will be initialized with a light-weight representation
65 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 */
67 public SparseArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070068 if (initialCapacity == 0) {
69 mKeys = EMPTY_INTS;
70 mValues = EMPTY_OBJECTS;
71 } else {
72 initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
73 mKeys = new int[initialCapacity];
74 mValues = new Object[initialCapacity];
75 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 mSize = 0;
77 }
78
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070079 @Override
80 @SuppressWarnings("unchecked")
81 public SparseArray<E> clone() {
82 SparseArray<E> clone = null;
83 try {
84 clone = (SparseArray<E>) super.clone();
85 clone.mKeys = mKeys.clone();
86 clone.mValues = mValues.clone();
87 } catch (CloneNotSupportedException cnse) {
88 /* ignore */
89 }
90 return clone;
91 }
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 /**
94 * Gets the Object mapped from the specified key, or <code>null</code>
95 * if no such mapping has been made.
96 */
97 public E get(int key) {
98 return get(key, null);
99 }
100
101 /**
102 * Gets the Object mapped from the specified key, or the specified Object
103 * if no such mapping has been made.
104 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700105 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 public E get(int key, E valueIfKeyNotFound) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700107 int i = binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
109 if (i < 0 || mValues[i] == DELETED) {
110 return valueIfKeyNotFound;
111 } else {
112 return (E) mValues[i];
113 }
114 }
115
116 /**
117 * Removes the mapping from the specified key, if there was any.
118 */
119 public void delete(int key) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700120 int i = binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
122 if (i >= 0) {
123 if (mValues[i] != DELETED) {
124 mValues[i] = DELETED;
125 mGarbage = true;
126 }
127 }
128 }
129
130 /**
131 * Alias for {@link #delete(int)}.
132 */
133 public void remove(int key) {
134 delete(key);
135 }
136
Dianne Hackbornc8017682010-07-06 13:34:38 -0700137 /**
138 * Removes the mapping at the specified index.
139 */
140 public void removeAt(int index) {
141 if (mValues[index] != DELETED) {
142 mValues[index] = DELETED;
143 mGarbage = true;
144 }
145 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private void gc() {
148 // Log.e("SparseArray", "gc start with " + mSize);
149
150 int n = mSize;
151 int o = 0;
152 int[] keys = mKeys;
153 Object[] values = mValues;
154
155 for (int i = 0; i < n; i++) {
156 Object val = values[i];
157
158 if (val != DELETED) {
159 if (i != o) {
160 keys[o] = keys[i];
161 values[o] = val;
Svetoslav Ganovd116d7c2011-11-21 18:41:59 -0800162 values[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 }
164
165 o++;
166 }
167 }
168
169 mGarbage = false;
170 mSize = o;
171
172 // Log.e("SparseArray", "gc end with " + mSize);
173 }
174
175 /**
176 * Adds a mapping from the specified key to the specified value,
177 * replacing the previous mapping from the specified key if there
178 * was one.
179 */
180 public void put(int key, E value) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700181 int i = binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
183 if (i >= 0) {
184 mValues[i] = value;
185 } else {
186 i = ~i;
187
188 if (i < mSize && mValues[i] == DELETED) {
189 mKeys[i] = key;
190 mValues[i] = value;
191 return;
192 }
193
194 if (mGarbage && mSize >= mKeys.length) {
195 gc();
196
197 // Search again because indices may have changed.
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700198 i = ~binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 }
200
201 if (mSize >= mKeys.length) {
202 int n = ArrayUtils.idealIntArraySize(mSize + 1);
203
204 int[] nkeys = new int[n];
205 Object[] nvalues = new Object[n];
206
207 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
208 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
209 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
210
211 mKeys = nkeys;
212 mValues = nvalues;
213 }
214
215 if (mSize - i != 0) {
216 // Log.e("SparseArray", "move " + (mSize - i));
217 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
218 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
219 }
220
221 mKeys[i] = key;
222 mValues[i] = value;
223 mSize++;
224 }
225 }
226
227 /**
228 * Returns the number of key-value mappings that this SparseArray
229 * currently stores.
230 */
231 public int size() {
232 if (mGarbage) {
233 gc();
234 }
235
236 return mSize;
237 }
238
239 /**
240 * Given an index in the range <code>0...size()-1</code>, returns
241 * the key from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700242 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 */
244 public int keyAt(int index) {
245 if (mGarbage) {
246 gc();
247 }
248
249 return mKeys[index];
250 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 /**
253 * Given an index in the range <code>0...size()-1</code>, returns
254 * the value from the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700255 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -0700257 @SuppressWarnings("unchecked")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 public E valueAt(int index) {
259 if (mGarbage) {
260 gc();
261 }
262
263 return (E) mValues[index];
264 }
265
266 /**
267 * Given an index in the range <code>0...size()-1</code>, sets a new
268 * value for the <code>index</code>th key-value mapping that this
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700269 * SparseArray stores.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 */
271 public void setValueAt(int index, E value) {
272 if (mGarbage) {
273 gc();
274 }
275
276 mValues[index] = value;
277 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 /**
280 * Returns the index for which {@link #keyAt} would return the
281 * specified key, or a negative number if the specified
282 * key is not mapped.
283 */
284 public int indexOfKey(int key) {
285 if (mGarbage) {
286 gc();
287 }
288
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700289 return binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 }
291
292 /**
293 * Returns an index for which {@link #valueAt} would return the
294 * specified key, or a negative number if no keys map to the
295 * specified value.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700296 * <p>Beware that this is a linear search, unlike lookups by key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 * and that multiple keys can map to the same value and this will
298 * find only one of them.
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700299 * <p>Note also that unlike most collections' {@code indexOf} methods,
300 * this method compares values using {@code ==} rather than {@code equals}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 */
302 public int indexOfValue(E value) {
303 if (mGarbage) {
304 gc();
305 }
306
307 for (int i = 0; i < mSize; i++)
308 if (mValues[i] == value)
309 return i;
310
311 return -1;
312 }
313
314 /**
315 * Removes all key-value mappings from this SparseArray.
316 */
317 public void clear() {
318 int n = mSize;
319 Object[] values = mValues;
320
321 for (int i = 0; i < n; i++) {
322 values[i] = null;
323 }
324
325 mSize = 0;
326 mGarbage = false;
327 }
328
329 /**
330 * Puts a key/value pair into the array, optimizing for the case where
331 * the key is greater than all existing keys in the array.
332 */
333 public void append(int key, E value) {
334 if (mSize != 0 && key <= mKeys[mSize - 1]) {
335 put(key, value);
336 return;
337 }
338
339 if (mGarbage && mSize >= mKeys.length) {
340 gc();
341 }
342
343 int pos = mSize;
344 if (pos >= mKeys.length) {
345 int n = ArrayUtils.idealIntArraySize(pos + 1);
346
347 int[] nkeys = new int[n];
348 Object[] nvalues = new Object[n];
349
350 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
351 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
352 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
353
354 mKeys = nkeys;
355 mValues = nvalues;
356 }
357
358 mKeys[pos] = key;
359 mValues[pos] = value;
360 mSize = pos + 1;
361 }
Elliott Hughes58aff7d2013-03-26 16:34:30 -0700362
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700363 // This is Arrays.binarySearch(), but doesn't do any argument validation.
364 static int binarySearch(int[] array, int size, int value) {
365 int lo = 0;
366 int hi = size - 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700368 while (lo <= hi) {
369 int mid = (lo + hi) >>> 1;
370 int midVal = array[mid];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700372 if (midVal < value) {
373 lo = mid + 1;
374 } else if (midVal > value) {
375 hi = mid - 1;
376 } else {
377 return mid; // value found
378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -0700380 return ~lo; // value not present
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382}