blob: 0835cb02e032d30bbc7a0df10cf09191ed54263b [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 * SparseIntArrays map integers to integers. Unlike a normal array of integers,
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 Integers, both because it avoids
25 * auto-boxing keys and values 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>
Flavio Lerda57713022013-09-08 18:04:58 +010035 *
36 * <p>It is possible to iterate over the items in this container using
37 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
38 * <code>keyAt(int)</code> with ascending values of the index will return the
39 * keys in ascending order, or the values corresponding to the keys in ascending
40 * order in the case of <code>valueAt(int)<code>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070042public class SparseIntArray implements Cloneable {
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070043 private int[] mKeys;
44 private int[] mValues;
45 private int mSize;
46
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 /**
48 * Creates a new SparseIntArray containing no mappings.
49 */
50 public SparseIntArray() {
51 this(10);
52 }
53
54 /**
55 * Creates a new SparseIntArray containing no mappings that will not
56 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070057 * number of mappings. If you supply an initial capacity of 0, the
58 * sparse array will be initialized with a light-weight representation
59 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 */
61 public SparseIntArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070062 if (initialCapacity == 0) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070063 mKeys = ContainerHelpers.EMPTY_INTS;
64 mValues = ContainerHelpers.EMPTY_INTS;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070065 } else {
66 initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
67 mKeys = new int[initialCapacity];
68 mValues = new int[initialCapacity];
69 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 mSize = 0;
71 }
72
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070073 @Override
74 public SparseIntArray clone() {
75 SparseIntArray clone = null;
76 try {
77 clone = (SparseIntArray) super.clone();
78 clone.mKeys = mKeys.clone();
79 clone.mValues = mValues.clone();
80 } catch (CloneNotSupportedException cnse) {
81 /* ignore */
82 }
83 return clone;
84 }
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /**
87 * Gets the int mapped from the specified key, or <code>0</code>
88 * if no such mapping has been made.
89 */
90 public int get(int key) {
91 return get(key, 0);
92 }
93
94 /**
95 * Gets the int mapped from the specified key, or the specified value
96 * if no such mapping has been made.
97 */
98 public int get(int key, int valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070099 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
101 if (i < 0) {
102 return valueIfKeyNotFound;
103 } else {
104 return mValues[i];
105 }
106 }
107
108 /**
109 * Removes the mapping from the specified key, if there was any.
110 */
111 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700112 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
114 if (i >= 0) {
115 removeAt(i);
116 }
117 }
118
119 /**
120 * Removes the mapping at the given index.
121 */
122 public void removeAt(int index) {
123 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
124 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
125 mSize--;
126 }
127
128 /**
129 * Adds a mapping from the specified key to the specified value,
130 * replacing the previous mapping from the specified key if there
131 * was one.
132 */
133 public void put(int key, int value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700134 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 if (i >= 0) {
137 mValues[i] = value;
138 } else {
139 i = ~i;
140
141 if (mSize >= mKeys.length) {
142 int n = ArrayUtils.idealIntArraySize(mSize + 1);
143
144 int[] nkeys = new int[n];
145 int[] nvalues = new int[n];
146
147 // Log.e("SparseIntArray", "grow " + mKeys.length + " to " + n);
148 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
149 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
150
151 mKeys = nkeys;
152 mValues = nvalues;
153 }
154
155 if (mSize - i != 0) {
156 // Log.e("SparseIntArray", "move " + (mSize - i));
157 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
158 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
159 }
160
161 mKeys[i] = key;
162 mValues[i] = value;
163 mSize++;
164 }
165 }
166
167 /**
168 * Returns the number of key-value mappings that this SparseIntArray
169 * currently stores.
170 */
171 public int size() {
172 return mSize;
173 }
174
175 /**
176 * Given an index in the range <code>0...size()-1</code>, returns
177 * the key from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100178 * SparseIntArray stores.
179 *
180 * <p>The keys corresponding to indices in ascending order are guaranteed to
181 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
182 * smallest key and <code>keyAt(size()-1)</code> will return the largest
183 * key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 */
185 public int keyAt(int index) {
186 return mKeys[index];
187 }
Flavio Lerda57713022013-09-08 18:04:58 +0100188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 /**
190 * Given an index in the range <code>0...size()-1</code>, returns
191 * the value from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100192 * SparseIntArray stores.
193 *
194 * <p>The values corresponding to indices in ascending order are guaranteed
195 * to be associated with keys in ascending order, e.g.,
196 * <code>valueAt(0)</code> will return the value associated with the
197 * smallest key and <code>valueAt(size()-1)</code> will return the value
198 * associated with the largest key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 */
200 public int valueAt(int index) {
201 return mValues[index];
202 }
203
204 /**
205 * Returns the index for which {@link #keyAt} would return the
206 * specified key, or a negative number if the specified
207 * key is not mapped.
208 */
209 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700210 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 }
212
213 /**
214 * Returns an index for which {@link #valueAt} would return the
215 * specified key, or a negative number if no keys map to the
216 * specified value.
217 * Beware that this is a linear search, unlike lookups by key,
218 * and that multiple keys can map to the same value and this will
219 * find only one of them.
220 */
221 public int indexOfValue(int value) {
222 for (int i = 0; i < mSize; i++)
223 if (mValues[i] == value)
224 return i;
225
226 return -1;
227 }
228
229 /**
230 * Removes all key-value mappings from this SparseIntArray.
231 */
232 public void clear() {
233 mSize = 0;
234 }
235
236 /**
237 * Puts a key/value pair into the array, optimizing for the case where
238 * the key is greater than all existing keys in the array.
239 */
240 public void append(int key, int value) {
241 if (mSize != 0 && key <= mKeys[mSize - 1]) {
242 put(key, value);
243 return;
244 }
245
246 int pos = mSize;
247 if (pos >= mKeys.length) {
248 int n = ArrayUtils.idealIntArraySize(pos + 1);
249
250 int[] nkeys = new int[n];
251 int[] nvalues = new int[n];
252
253 // Log.e("SparseIntArray", "grow " + mKeys.length + " to " + n);
254 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
255 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
256
257 mKeys = nkeys;
258 mValues = nvalues;
259 }
260
261 mKeys[pos] = key;
262 mValues[pos] = value;
263 mSize = pos + 1;
264 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700265
266 /**
267 * {@inheritDoc}
268 *
269 * <p>This implementation composes a string by iterating over its mappings.
270 */
271 @Override
272 public String toString() {
273 if (size() <= 0) {
274 return "{}";
275 }
276
277 StringBuilder buffer = new StringBuilder(mSize * 28);
278 buffer.append('{');
279 for (int i=0; i<mSize; i++) {
280 if (i > 0) {
281 buffer.append(", ");
282 }
283 int key = keyAt(i);
284 buffer.append(key);
285 buffer.append('=');
286 int value = valueAt(i);
287 buffer.append(value);
288 }
289 buffer.append('}');
290 return buffer.toString();
291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292}