blob: d6e0e53a210dd64a8a34cea13323376a69eeac60 [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
Kweku Adams025a1662019-03-30 00:03:17 +000019import android.annotation.UnsupportedAppUsage;
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050022import com.android.internal.util.GrowingArrayUtils;
23
24import libcore.util.EmptyArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26/**
27 * SparseBooleanArrays map integers to booleans.
28 * Unlike a normal array of booleans
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 Booleans, 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 SparseBooleanArray implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049 /**
50 * Creates a new SparseBooleanArray containing no mappings.
51 */
52 public SparseBooleanArray() {
53 this(10);
54 }
55
56 /**
57 * Creates a new SparseBooleanArray containing no mappings that will not
58 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070059 * number of mappings. If you supply an initial capacity of 0, the
60 * sparse array will be initialized with a light-weight representation
61 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 */
63 public SparseBooleanArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070064 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050065 mKeys = EmptyArray.INT;
66 mValues = EmptyArray.BOOLEAN;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070067 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050068 mKeys = ArrayUtils.newUnpaddedIntArray(initialCapacity);
69 mValues = new boolean[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 mSize = 0;
72 }
73
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070074 @Override
75 public SparseBooleanArray clone() {
76 SparseBooleanArray clone = null;
77 try {
78 clone = (SparseBooleanArray) super.clone();
79 clone.mKeys = mKeys.clone();
80 clone.mValues = mValues.clone();
81 } catch (CloneNotSupportedException cnse) {
82 /* ignore */
83 }
84 return clone;
85 }
86
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 /**
88 * Gets the boolean mapped from the specified key, or <code>false</code>
89 * if no such mapping has been made.
90 */
91 public boolean get(int key) {
92 return get(key, false);
93 }
94
95 /**
96 * Gets the boolean mapped from the specified key, or the specified value
97 * if no such mapping has been made.
98 */
99 public boolean get(int key, boolean valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700100 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102 if (i < 0) {
103 return valueIfKeyNotFound;
104 } else {
105 return mValues[i];
106 }
107 }
108
109 /**
110 * Removes the mapping from the specified key, if there was any.
111 */
112 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700113 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
115 if (i >= 0) {
116 System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1));
117 System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1));
118 mSize--;
119 }
120 }
121
Jake Whartond77bce82017-12-21 16:59:54 -0500122 /**
123 * Removes the mapping at the specified index.
124 * <p>
125 * For indices outside of the range {@code 0...size()-1}, the behavior is undefined.
126 */
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800127 public void removeAt(int index) {
128 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
129 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
130 mSize--;
131 }
132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 /**
134 * Adds a mapping from the specified key to the specified value,
135 * replacing the previous mapping from the specified key if there
136 * was one.
137 */
138 public void put(int key, boolean value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700139 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 if (i >= 0) {
142 mValues[i] = value;
143 } else {
144 i = ~i;
145
Adam Lesinski776abc22014-03-07 11:30:59 -0500146 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
147 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 mSize++;
149 }
150 }
151
152 /**
153 * Returns the number of key-value mappings that this SparseBooleanArray
154 * currently stores.
155 */
156 public int size() {
157 return mSize;
158 }
159
160 /**
161 * Given an index in the range <code>0...size()-1</code>, returns
162 * the key from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100163 * SparseBooleanArray stores.
164 *
165 * <p>The keys corresponding to indices in ascending order are guaranteed to
166 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
167 * smallest key and <code>keyAt(size()-1)</code> will return the largest
168 * key.</p>
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700169 *
170 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
171 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
172 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
173 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 */
175 public int keyAt(int index) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700176 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000177 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700178 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000179 throw new ArrayIndexOutOfBoundsException(index);
180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 return mKeys[index];
182 }
Flavio Lerda57713022013-09-08 18:04:58 +0100183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 /**
185 * Given an index in the range <code>0...size()-1</code>, returns
186 * the value from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100187 * SparseBooleanArray stores.
188 *
189 * <p>The values corresponding to indices in ascending order are guaranteed
190 * to be associated with keys in ascending order, e.g.,
191 * <code>valueAt(0)</code> will return the value associated with the
192 * smallest key and <code>valueAt(size()-1)</code> will return the value
193 * associated with the largest key.</p>
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700194 *
195 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
196 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
197 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
198 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 */
200 public boolean valueAt(int index) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700201 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000202 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700203 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000204 throw new ArrayIndexOutOfBoundsException(index);
205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 return mValues[index];
207 }
208
Jake Whartona8a04352018-09-29 01:52:24 -0400209 /**
210 * Directly set the value at a particular index.
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700211 *
212 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
213 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
214 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
215 * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
Jake Whartona8a04352018-09-29 01:52:24 -0400216 */
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800217 public void setValueAt(int index, boolean value) {
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700218 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
Kweku Adams025a1662019-03-30 00:03:17 +0000219 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
Kweku Adams3858b2d2019-04-29 11:47:41 -0700220 // Check if exception should be thrown outside of the critical path.
Kweku Adams025a1662019-03-30 00:03:17 +0000221 throw new ArrayIndexOutOfBoundsException(index);
222 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800223 mValues[index] = value;
224 }
225
Steve McKay4b3a13c2015-06-11 10:10:49 -0700226 /** @hide */
227 public void setKeyAt(int index, int key) {
Kweku Adams025a1662019-03-30 00:03:17 +0000228 if (index >= mSize) {
229 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
230 throw new ArrayIndexOutOfBoundsException(index);
231 }
Steve McKay4b3a13c2015-06-11 10:10:49 -0700232 mKeys[index] = key;
233 }
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 /**
236 * Returns the index for which {@link #keyAt} would return the
237 * specified key, or a negative number if the specified
238 * key is not mapped.
239 */
240 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700241 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 }
243
244 /**
245 * Returns an index for which {@link #valueAt} would return the
246 * specified key, or a negative number if no keys map to the
247 * specified value.
248 * Beware that this is a linear search, unlike lookups by key,
249 * and that multiple keys can map to the same value and this will
250 * find only one of them.
251 */
252 public int indexOfValue(boolean value) {
253 for (int i = 0; i < mSize; i++)
254 if (mValues[i] == value)
255 return i;
256
257 return -1;
258 }
259
260 /**
261 * Removes all key-value mappings from this SparseBooleanArray.
262 */
263 public void clear() {
264 mSize = 0;
265 }
266
267 /**
268 * Puts a key/value pair into the array, optimizing for the case where
269 * the key is greater than all existing keys in the array.
270 */
271 public void append(int key, boolean value) {
272 if (mSize != 0 && key <= mKeys[mSize - 1]) {
273 put(key, value);
274 return;
275 }
276
Adam Lesinski776abc22014-03-07 11:30:59 -0500277 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
278 mValues = GrowingArrayUtils.append(mValues, mSize, value);
279 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700281
Steve McKay3b409d02015-07-22 11:42:14 -0700282 @Override
283 public int hashCode() {
284 int hashCode = mSize;
285 for (int i = 0; i < mSize; i++) {
286 hashCode = 31 * hashCode + mKeys[i] | (mValues[i] ? 1 : 0);
287 }
288 return hashCode;
289 }
290
291 @Override
292 public boolean equals(Object that) {
293 if (this == that) {
294 return true;
295 }
296
297 if (!(that instanceof SparseBooleanArray)) {
298 return false;
299 }
300
301 SparseBooleanArray other = (SparseBooleanArray) that;
302 if (mSize != other.mSize) {
303 return false;
304 }
305
306 for (int i = 0; i < mSize; i++) {
307 if (mKeys[i] != other.mKeys[i]) {
308 return false;
309 }
310 if (mValues[i] != other.mValues[i]) {
311 return false;
312 }
313 }
314 return true;
315 }
316
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700317 /**
318 * {@inheritDoc}
319 *
320 * <p>This implementation composes a string by iterating over its mappings.
321 */
322 @Override
323 public String toString() {
324 if (size() <= 0) {
325 return "{}";
326 }
327
328 StringBuilder buffer = new StringBuilder(mSize * 28);
329 buffer.append('{');
330 for (int i=0; i<mSize; i++) {
331 if (i > 0) {
332 buffer.append(", ");
333 }
334 int key = keyAt(i);
335 buffer.append(key);
336 buffer.append('=');
337 boolean value = valueAt(i);
338 buffer.append(value);
339 }
340 buffer.append('}');
341 return buffer.toString();
342 }
343
Jake Whartona8a04352018-09-29 01:52:24 -0400344 @UnsupportedAppUsage(maxTargetSdk = 28) // Use keyAt(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 private int[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -0400346 @UnsupportedAppUsage(maxTargetSdk = 28) // Use valueAt(int), setValueAt(int, boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 private boolean[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -0400348 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 private int mSize;
350}