blob: e5c729d3dd44e63b34d3e16fbf19a8f0c8ab3765 [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 * SparseIntArrays map integers to integers. Unlike a normal array of integers,
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 Integers, both because it avoids
28 * auto-boxing keys and values 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>
Flavio Lerda57713022013-09-08 18:04:58 +010038 *
39 * <p>It is possible to iterate over the items in this container using
40 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
41 * <code>keyAt(int)</code> with ascending values of the index will return the
42 * keys in ascending order, or the values corresponding to the keys in ascending
Newton Allenebb47952013-11-21 13:27:10 -080043 * order in the case of <code>valueAt(int)</code>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070045public class SparseIntArray implements Cloneable {
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070046 private int[] mKeys;
47 private int[] mValues;
48 private int mSize;
49
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 /**
51 * Creates a new SparseIntArray containing no mappings.
52 */
53 public SparseIntArray() {
54 this(10);
55 }
56
57 /**
58 * Creates a new SparseIntArray containing no mappings that will not
59 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070060 * number of mappings. If you supply an initial capacity of 0, the
61 * sparse array will be initialized with a light-weight representation
62 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 */
64 public SparseIntArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070065 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050066 mKeys = EmptyArray.INT;
67 mValues = EmptyArray.INT;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070068 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050069 mKeys = ArrayUtils.newUnpaddedIntArray(initialCapacity);
70 mValues = new int[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 mSize = 0;
73 }
74
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070075 @Override
76 public SparseIntArray clone() {
77 SparseIntArray clone = null;
78 try {
79 clone = (SparseIntArray) super.clone();
80 clone.mKeys = mKeys.clone();
81 clone.mValues = mValues.clone();
82 } catch (CloneNotSupportedException cnse) {
83 /* ignore */
84 }
85 return clone;
86 }
87
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 /**
89 * Gets the int mapped from the specified key, or <code>0</code>
90 * if no such mapping has been made.
91 */
92 public int get(int key) {
93 return get(key, 0);
94 }
95
96 /**
97 * Gets the int mapped from the specified key, or the specified value
98 * if no such mapping has been made.
99 */
100 public int get(int key, int valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700101 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
103 if (i < 0) {
104 return valueIfKeyNotFound;
105 } else {
106 return mValues[i];
107 }
108 }
109
110 /**
111 * Removes the mapping from the specified key, if there was any.
112 */
113 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700114 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
116 if (i >= 0) {
117 removeAt(i);
118 }
119 }
120
121 /**
122 * Removes the mapping at the given index.
123 */
124 public void removeAt(int index) {
125 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
126 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
127 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, int value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700136 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
138 if (i >= 0) {
139 mValues[i] = value;
140 } else {
141 i = ~i;
142
Adam Lesinski776abc22014-03-07 11:30:59 -0500143 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
144 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 mSize++;
146 }
147 }
148
149 /**
150 * Returns the number of key-value mappings that this SparseIntArray
151 * currently stores.
152 */
153 public int size() {
154 return mSize;
155 }
156
157 /**
158 * Given an index in the range <code>0...size()-1</code>, returns
159 * the key from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100160 * SparseIntArray stores.
161 *
162 * <p>The keys corresponding to indices in ascending order are guaranteed to
163 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
164 * smallest key and <code>keyAt(size()-1)</code> will return the largest
165 * key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 */
167 public int keyAt(int index) {
168 return mKeys[index];
169 }
Flavio Lerda57713022013-09-08 18:04:58 +0100170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 /**
172 * Given an index in the range <code>0...size()-1</code>, returns
173 * the value from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100174 * SparseIntArray stores.
175 *
176 * <p>The values corresponding to indices in ascending order are guaranteed
177 * to be associated with keys in ascending order, e.g.,
178 * <code>valueAt(0)</code> will return the value associated with the
179 * smallest key and <code>valueAt(size()-1)</code> will return the value
180 * associated with the largest key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 */
182 public int valueAt(int index) {
183 return mValues[index];
184 }
185
186 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700187 * Directly set the value at a particular index.
188 * @hide
189 */
190 public void setValueAt(int index, int value) {
191 mValues[index] = value;
192 }
193
194 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 * Returns the index for which {@link #keyAt} would return the
196 * specified key, or a negative number if the specified
197 * key is not mapped.
198 */
199 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700200 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 }
202
203 /**
204 * Returns an index for which {@link #valueAt} would return the
205 * specified key, or a negative number if no keys map to the
206 * specified value.
207 * Beware that this is a linear search, unlike lookups by key,
208 * and that multiple keys can map to the same value and this will
209 * find only one of them.
210 */
211 public int indexOfValue(int value) {
212 for (int i = 0; i < mSize; i++)
213 if (mValues[i] == value)
214 return i;
215
216 return -1;
217 }
218
219 /**
220 * Removes all key-value mappings from this SparseIntArray.
221 */
222 public void clear() {
223 mSize = 0;
224 }
225
226 /**
227 * Puts a key/value pair into the array, optimizing for the case where
228 * the key is greater than all existing keys in the array.
229 */
230 public void append(int key, int value) {
231 if (mSize != 0 && key <= mKeys[mSize - 1]) {
232 put(key, value);
233 return;
234 }
235
Adam Lesinski776abc22014-03-07 11:30:59 -0500236 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
237 mValues = GrowingArrayUtils.append(mValues, mSize, value);
238 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700240
241 /**
242 * {@inheritDoc}
243 *
244 * <p>This implementation composes a string by iterating over its mappings.
245 */
246 @Override
247 public String toString() {
248 if (size() <= 0) {
249 return "{}";
250 }
251
252 StringBuilder buffer = new StringBuilder(mSize * 28);
253 buffer.append('{');
254 for (int i=0; i<mSize; i++) {
255 if (i > 0) {
256 buffer.append(", ");
257 }
258 int key = keyAt(i);
259 buffer.append(key);
260 buffer.append('=');
261 int value = valueAt(i);
262 buffer.append(value);
263 }
264 buffer.append('}');
265 return buffer.toString();
266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267}