blob: 9e6bad1d9ae0b4aa86d5e8d20f74c91c924e6e56 [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
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -070022import java.util.Arrays;
23
Mathew Inwood4eb56ab2018-08-14 17:24:32 +010024import android.annotation.UnsupportedAppUsage;
Adam Lesinski776abc22014-03-07 11:30:59 -050025import libcore.util.EmptyArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27/**
28 * SparseIntArrays map integers to integers. Unlike a normal array of integers,
Dianne Hackbornb993f412013-07-12 17:46:45 -070029 * there can be gaps in the indices. It is intended to be more memory efficient
30 * than using a HashMap to map Integers to Integers, both because it avoids
31 * auto-boxing keys and values and its data structure doesn't rely on an extra entry object
32 * for each mapping.
33 *
34 * <p>Note that this container keeps its mappings in an array data structure,
35 * using a binary search to find keys. The implementation is not intended to be appropriate for
36 * data structures
37 * that may contain large numbers of items. It is generally slower than a traditional
38 * HashMap, since lookups require a binary search and adds and removes require inserting
39 * and deleting entries in the array. For containers holding up to hundreds of items,
40 * the performance difference is not significant, less than 50%.</p>
Flavio Lerda57713022013-09-08 18:04:58 +010041 *
42 * <p>It is possible to iterate over the items in this container using
43 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
44 * <code>keyAt(int)</code> with ascending values of the index will return the
45 * keys in ascending order, or the values corresponding to the keys in ascending
Newton Allenebb47952013-11-21 13:27:10 -080046 * order in the case of <code>valueAt(int)</code>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070048public class SparseIntArray implements Cloneable {
Jake Whartona8a04352018-09-29 01:52:24 -040049 @UnsupportedAppUsage(maxTargetSdk = 28) // Use keyAt(int)
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070050 private int[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -040051 @UnsupportedAppUsage(maxTargetSdk = 28) // Use valueAt(int), setValueAt(int, int)
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070052 private int[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -040053 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size()
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070054 private int mSize;
55
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 /**
57 * Creates a new SparseIntArray containing no mappings.
58 */
59 public SparseIntArray() {
60 this(10);
61 }
62
63 /**
64 * Creates a new SparseIntArray containing no mappings that will not
65 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070066 * number of mappings. If you supply an initial capacity of 0, the
67 * sparse array will be initialized with a light-weight representation
68 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 */
70 public SparseIntArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070071 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050072 mKeys = EmptyArray.INT;
73 mValues = EmptyArray.INT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070074 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050075 mKeys = ArrayUtils.newUnpaddedIntArray(initialCapacity);
76 mValues = new int[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 mSize = 0;
79 }
80
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070081 @Override
82 public SparseIntArray clone() {
83 SparseIntArray clone = null;
84 try {
85 clone = (SparseIntArray) super.clone();
86 clone.mKeys = mKeys.clone();
87 clone.mValues = mValues.clone();
88 } catch (CloneNotSupportedException cnse) {
89 /* ignore */
90 }
91 return clone;
92 }
93
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 /**
95 * Gets the int mapped from the specified key, or <code>0</code>
96 * if no such mapping has been made.
97 */
98 public int get(int key) {
99 return get(key, 0);
100 }
101
102 /**
103 * Gets the int mapped from the specified key, or the specified value
104 * if no such mapping has been made.
105 */
106 public int get(int key, int valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700107 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
109 if (i < 0) {
110 return valueIfKeyNotFound;
111 } else {
112 return 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 Hackborn3e82ba12013-07-16 13:23:55 -0700120 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
122 if (i >= 0) {
123 removeAt(i);
124 }
125 }
126
127 /**
128 * Removes the mapping at the given index.
129 */
130 public void removeAt(int index) {
131 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
132 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
133 mSize--;
134 }
135
136 /**
137 * Adds a mapping from the specified key to the specified value,
138 * replacing the previous mapping from the specified key if there
139 * was one.
140 */
141 public void put(int key, int value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700142 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 if (i >= 0) {
145 mValues[i] = value;
146 } else {
147 i = ~i;
148
Adam Lesinski776abc22014-03-07 11:30:59 -0500149 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
150 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 mSize++;
152 }
153 }
154
155 /**
156 * Returns the number of key-value mappings that this SparseIntArray
157 * currently stores.
158 */
159 public int size() {
160 return mSize;
161 }
162
163 /**
164 * Given an index in the range <code>0...size()-1</code>, returns
165 * the key from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100166 * SparseIntArray stores.
167 *
168 * <p>The keys corresponding to indices in ascending order are guaranteed to
169 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
170 * smallest key and <code>keyAt(size()-1)</code> will return the largest
171 * key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 */
173 public int keyAt(int index) {
174 return mKeys[index];
175 }
Flavio Lerda57713022013-09-08 18:04:58 +0100176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 /**
178 * Given an index in the range <code>0...size()-1</code>, returns
179 * the value from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100180 * SparseIntArray stores.
181 *
182 * <p>The values corresponding to indices in ascending order are guaranteed
183 * to be associated with keys in ascending order, e.g.,
184 * <code>valueAt(0)</code> will return the value associated with the
185 * smallest key and <code>valueAt(size()-1)</code> will return the value
186 * associated with the largest key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 */
188 public int valueAt(int index) {
189 return mValues[index];
190 }
191
192 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700193 * Directly set the value at a particular index.
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700194 */
195 public void setValueAt(int index, int value) {
196 mValues[index] = value;
197 }
198
199 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 * Returns the index for which {@link #keyAt} would return the
201 * specified key, or a negative number if the specified
202 * key is not mapped.
203 */
204 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700205 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 }
207
208 /**
209 * Returns an index for which {@link #valueAt} would return the
210 * specified key, or a negative number if no keys map to the
211 * specified value.
212 * Beware that this is a linear search, unlike lookups by key,
213 * and that multiple keys can map to the same value and this will
214 * find only one of them.
215 */
216 public int indexOfValue(int value) {
217 for (int i = 0; i < mSize; i++)
218 if (mValues[i] == value)
219 return i;
220
221 return -1;
222 }
223
224 /**
225 * Removes all key-value mappings from this SparseIntArray.
226 */
227 public void clear() {
228 mSize = 0;
229 }
230
231 /**
232 * Puts a key/value pair into the array, optimizing for the case where
233 * the key is greater than all existing keys in the array.
234 */
235 public void append(int key, int value) {
236 if (mSize != 0 && key <= mKeys[mSize - 1]) {
237 put(key, value);
238 return;
239 }
240
Adam Lesinski776abc22014-03-07 11:30:59 -0500241 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
242 mValues = GrowingArrayUtils.append(mValues, mSize, value);
243 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700245
246 /**
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700247 * Provides a copy of keys.
248 *
249 * @hide
250 * */
251 public int[] copyKeys() {
252 if (size() == 0) {
253 return null;
254 }
255 return Arrays.copyOf(mKeys, size());
256 }
257
258 /**
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700259 * {@inheritDoc}
260 *
261 * <p>This implementation composes a string by iterating over its mappings.
262 */
263 @Override
264 public String toString() {
265 if (size() <= 0) {
266 return "{}";
267 }
268
269 StringBuilder buffer = new StringBuilder(mSize * 28);
270 buffer.append('{');
271 for (int i=0; i<mSize; i++) {
272 if (i > 0) {
273 buffer.append(", ");
274 }
275 int key = keyAt(i);
276 buffer.append(key);
277 buffer.append('=');
278 int value = valueAt(i);
279 buffer.append(value);
280 }
281 buffer.append('}');
282 return buffer.toString();
283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284}