blob: 7fc43b92c5490100796a5747d203a1e0cea0c0c2 [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,
23 * there can be gaps in the indices. It is intended to be more efficient
24 * than using a HashMap to map Integers to Objects.
25 */
26public class SparseArray<E> {
27 private static final Object DELETED = new Object();
28 private boolean mGarbage = false;
29
30 /**
31 * Creates a new SparseArray containing no mappings.
32 */
33 public SparseArray() {
34 this(10);
35 }
36
37 /**
38 * Creates a new SparseArray containing no mappings that will not
39 * require any additional memory allocation to store the specified
40 * number of mappings.
41 */
42 public SparseArray(int initialCapacity) {
43 initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
44
45 mKeys = new int[initialCapacity];
46 mValues = new Object[initialCapacity];
47 mSize = 0;
48 }
49
50 /**
51 * Gets the Object mapped from the specified key, or <code>null</code>
52 * if no such mapping has been made.
53 */
54 public E get(int key) {
55 return get(key, null);
56 }
57
58 /**
59 * Gets the Object mapped from the specified key, or the specified Object
60 * if no such mapping has been made.
61 */
62 public E get(int key, E valueIfKeyNotFound) {
63 int i = binarySearch(mKeys, 0, mSize, key);
64
65 if (i < 0 || mValues[i] == DELETED) {
66 return valueIfKeyNotFound;
67 } else {
68 return (E) mValues[i];
69 }
70 }
71
72 /**
73 * Removes the mapping from the specified key, if there was any.
74 */
75 public void delete(int key) {
76 int i = binarySearch(mKeys, 0, mSize, key);
77
78 if (i >= 0) {
79 if (mValues[i] != DELETED) {
80 mValues[i] = DELETED;
81 mGarbage = true;
82 }
83 }
84 }
85
86 /**
87 * Alias for {@link #delete(int)}.
88 */
89 public void remove(int key) {
90 delete(key);
91 }
92
Dianne Hackbornc8017682010-07-06 13:34:38 -070093 /**
94 * Removes the mapping at the specified index.
95 */
96 public void removeAt(int index) {
97 if (mValues[index] != DELETED) {
98 mValues[index] = DELETED;
99 mGarbage = true;
100 }
101 }
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private void gc() {
104 // Log.e("SparseArray", "gc start with " + mSize);
105
106 int n = mSize;
107 int o = 0;
108 int[] keys = mKeys;
109 Object[] values = mValues;
110
111 for (int i = 0; i < n; i++) {
112 Object val = values[i];
113
114 if (val != DELETED) {
115 if (i != o) {
116 keys[o] = keys[i];
117 values[o] = val;
118 }
119
120 o++;
121 }
122 }
123
124 mGarbage = false;
125 mSize = o;
126
127 // Log.e("SparseArray", "gc end with " + mSize);
128 }
129
130 /**
131 * Adds a mapping from the specified key to the specified value,
132 * replacing the previous mapping from the specified key if there
133 * was one.
134 */
135 public void put(int key, E value) {
136 int i = binarySearch(mKeys, 0, mSize, key);
137
138 if (i >= 0) {
139 mValues[i] = value;
140 } else {
141 i = ~i;
142
143 if (i < mSize && mValues[i] == DELETED) {
144 mKeys[i] = key;
145 mValues[i] = value;
146 return;
147 }
148
149 if (mGarbage && mSize >= mKeys.length) {
150 gc();
151
152 // Search again because indices may have changed.
153 i = ~binarySearch(mKeys, 0, mSize, key);
154 }
155
156 if (mSize >= mKeys.length) {
157 int n = ArrayUtils.idealIntArraySize(mSize + 1);
158
159 int[] nkeys = new int[n];
160 Object[] nvalues = new Object[n];
161
162 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
163 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
164 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
165
166 mKeys = nkeys;
167 mValues = nvalues;
168 }
169
170 if (mSize - i != 0) {
171 // Log.e("SparseArray", "move " + (mSize - i));
172 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
173 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
174 }
175
176 mKeys[i] = key;
177 mValues[i] = value;
178 mSize++;
179 }
180 }
181
182 /**
183 * Returns the number of key-value mappings that this SparseArray
184 * currently stores.
185 */
186 public int size() {
187 if (mGarbage) {
188 gc();
189 }
190
191 return mSize;
192 }
193
194 /**
195 * Given an index in the range <code>0...size()-1</code>, returns
196 * the key from the <code>index</code>th key-value mapping that this
197 * SparseArray stores.
198 */
199 public int keyAt(int index) {
200 if (mGarbage) {
201 gc();
202 }
203
204 return mKeys[index];
205 }
206
207 /**
208 * Given an index in the range <code>0...size()-1</code>, returns
209 * the value from the <code>index</code>th key-value mapping that this
210 * SparseArray stores.
211 */
212 public E valueAt(int index) {
213 if (mGarbage) {
214 gc();
215 }
216
217 return (E) mValues[index];
218 }
219
220 /**
221 * Given an index in the range <code>0...size()-1</code>, sets a new
222 * value for the <code>index</code>th key-value mapping that this
223 * SparseArray stores.
224 */
225 public void setValueAt(int index, E value) {
226 if (mGarbage) {
227 gc();
228 }
229
230 mValues[index] = value;
231 }
232
233 /**
234 * Returns the index for which {@link #keyAt} would return the
235 * specified key, or a negative number if the specified
236 * key is not mapped.
237 */
238 public int indexOfKey(int key) {
239 if (mGarbage) {
240 gc();
241 }
242
243 return binarySearch(mKeys, 0, mSize, key);
244 }
245
246 /**
247 * Returns an index for which {@link #valueAt} would return the
248 * specified key, or a negative number if no keys map to the
249 * specified value.
250 * Beware that this is a linear search, unlike lookups by key,
251 * and that multiple keys can map to the same value and this will
252 * find only one of them.
253 */
254 public int indexOfValue(E value) {
255 if (mGarbage) {
256 gc();
257 }
258
259 for (int i = 0; i < mSize; i++)
260 if (mValues[i] == value)
261 return i;
262
263 return -1;
264 }
265
266 /**
267 * Removes all key-value mappings from this SparseArray.
268 */
269 public void clear() {
270 int n = mSize;
271 Object[] values = mValues;
272
273 for (int i = 0; i < n; i++) {
274 values[i] = null;
275 }
276
277 mSize = 0;
278 mGarbage = false;
279 }
280
281 /**
282 * Puts a key/value pair into the array, optimizing for the case where
283 * the key is greater than all existing keys in the array.
284 */
285 public void append(int key, E value) {
286 if (mSize != 0 && key <= mKeys[mSize - 1]) {
287 put(key, value);
288 return;
289 }
290
291 if (mGarbage && mSize >= mKeys.length) {
292 gc();
293 }
294
295 int pos = mSize;
296 if (pos >= mKeys.length) {
297 int n = ArrayUtils.idealIntArraySize(pos + 1);
298
299 int[] nkeys = new int[n];
300 Object[] nvalues = new Object[n];
301
302 // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
303 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
304 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
305
306 mKeys = nkeys;
307 mValues = nvalues;
308 }
309
310 mKeys[pos] = key;
311 mValues[pos] = value;
312 mSize = pos + 1;
313 }
314
315 private static int binarySearch(int[] a, int start, int len, int key) {
316 int high = start + len, low = start - 1, guess;
317
318 while (high - low > 1) {
319 guess = (high + low) / 2;
320
321 if (a[guess] < key)
322 low = guess;
323 else
324 high = guess;
325 }
326
327 if (high == start + len)
328 return ~(start + len);
329 else if (a[high] == key)
330 return high;
331 else
332 return ~high;
333 }
334
335 private void checkIntegrity() {
336 for (int i = 1; i < mSize; i++) {
337 if (mKeys[i] <= mKeys[i - 1]) {
338 for (int j = 0; j < mSize; j++) {
339 Log.e("FAIL", j + ": " + mKeys[j] + " -> " + mValues[j]);
340 }
341
342 throw new RuntimeException();
343 }
344 }
345 }
346
347 private int[] mKeys;
348 private Object[] mValues;
349 private int mSize;
350}