blob: d4c40954bdd10c6db0c826861af72ac847e1bd89 [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
Mathew Inwood4eb56ab2018-08-14 17:24:32 +010022import android.annotation.UnsupportedAppUsage;
Adam Lesinski776abc22014-03-07 11:30:59 -050023import libcore.util.EmptyArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25/**
26 * SparseBooleanArrays map integers to booleans.
27 * Unlike a normal array of booleans
Dianne Hackbornb993f412013-07-12 17:46:45 -070028 * there can be gaps in the indices. It is intended to be more memory efficient
29 * than using a HashMap to map Integers to Booleans, both because it avoids
30 * auto-boxing keys and values and its data structure doesn't rely on an extra entry object
31 * for each mapping.
32 *
33 * <p>Note that this container keeps its mappings in an array data structure,
34 * using a binary search to find keys. The implementation is not intended to be appropriate for
35 * data structures
36 * that may contain large numbers of items. It is generally slower than a traditional
37 * HashMap, since lookups require a binary search and adds and removes require inserting
38 * and deleting entries in the array. For containers holding up to hundreds of items,
39 * the performance difference is not significant, less than 50%.</p>
Flavio Lerda57713022013-09-08 18:04:58 +010040 *
41 * <p>It is possible to iterate over the items in this container using
42 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
43 * <code>keyAt(int)</code> with ascending values of the index will return the
44 * keys in ascending order, or the values corresponding to the keys in ascending
Newton Allenebb47952013-11-21 13:27:10 -080045 * order in the case of <code>valueAt(int)</code>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046 */
Svetoslav Ganov35bfede2011-07-14 17:57:06 -070047public class SparseBooleanArray implements Cloneable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048 /**
49 * Creates a new SparseBooleanArray containing no mappings.
50 */
51 public SparseBooleanArray() {
52 this(10);
53 }
54
55 /**
56 * Creates a new SparseBooleanArray containing no mappings that will not
57 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070058 * number of mappings. If you supply an initial capacity of 0, the
59 * sparse array will be initialized with a light-weight representation
60 * not requiring any additional array allocations.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 */
62 public SparseBooleanArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070063 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050064 mKeys = EmptyArray.INT;
65 mValues = EmptyArray.BOOLEAN;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070066 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050067 mKeys = ArrayUtils.newUnpaddedIntArray(initialCapacity);
68 mValues = new boolean[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070069 }
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 SparseBooleanArray clone() {
75 SparseBooleanArray clone = null;
76 try {
77 clone = (SparseBooleanArray) 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 boolean mapped from the specified key, or <code>false</code>
88 * if no such mapping has been made.
89 */
90 public boolean get(int key) {
91 return get(key, false);
92 }
93
94 /**
95 * Gets the boolean mapped from the specified key, or the specified value
96 * if no such mapping has been made.
97 */
98 public boolean get(int key, boolean 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 System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1));
116 System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1));
117 mSize--;
118 }
119 }
120
Jake Whartond77bce82017-12-21 16:59:54 -0500121 /**
122 * Removes the mapping at the specified index.
123 * <p>
124 * For indices outside of the range {@code 0...size()-1}, the behavior is undefined.
125 */
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800126 public void removeAt(int index) {
127 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
128 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
129 mSize--;
130 }
131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 /**
133 * Adds a mapping from the specified key to the specified value,
134 * replacing the previous mapping from the specified key if there
135 * was one.
136 */
137 public void put(int key, boolean value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700138 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
140 if (i >= 0) {
141 mValues[i] = value;
142 } else {
143 i = ~i;
144
Adam Lesinski776abc22014-03-07 11:30:59 -0500145 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
146 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 mSize++;
148 }
149 }
150
151 /**
152 * Returns the number of key-value mappings that this SparseBooleanArray
153 * currently stores.
154 */
155 public int size() {
156 return mSize;
157 }
158
159 /**
160 * Given an index in the range <code>0...size()-1</code>, returns
161 * the key from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100162 * SparseBooleanArray stores.
163 *
164 * <p>The keys corresponding to indices in ascending order are guaranteed to
165 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
166 * smallest key and <code>keyAt(size()-1)</code> will return the largest
167 * key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 */
169 public int keyAt(int index) {
170 return mKeys[index];
171 }
Flavio Lerda57713022013-09-08 18:04:58 +0100172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 /**
174 * Given an index in the range <code>0...size()-1</code>, returns
175 * the value from the <code>index</code>th key-value mapping that this
Flavio Lerda57713022013-09-08 18:04:58 +0100176 * SparseBooleanArray stores.
177 *
178 * <p>The values corresponding to indices in ascending order are guaranteed
179 * to be associated with keys in ascending order, e.g.,
180 * <code>valueAt(0)</code> will return the value associated with the
181 * smallest key and <code>valueAt(size()-1)</code> will return the value
182 * associated with the largest key.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 */
184 public boolean valueAt(int index) {
185 return mValues[index];
186 }
187
Jake Whartona8a04352018-09-29 01:52:24 -0400188 /**
189 * Directly set the value at a particular index.
190 */
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800191 public void setValueAt(int index, boolean value) {
192 mValues[index] = value;
193 }
194
Steve McKay4b3a13c2015-06-11 10:10:49 -0700195 /** @hide */
196 public void setKeyAt(int index, int key) {
197 mKeys[index] = key;
198 }
199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 /**
201 * Returns the index for which {@link #keyAt} would return the
202 * specified key, or a negative number if the specified
203 * key is not mapped.
204 */
205 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700206 return ContainerHelpers.binarySearch(mKeys, mSize, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 }
208
209 /**
210 * Returns an index for which {@link #valueAt} would return the
211 * specified key, or a negative number if no keys map to the
212 * specified value.
213 * Beware that this is a linear search, unlike lookups by key,
214 * and that multiple keys can map to the same value and this will
215 * find only one of them.
216 */
217 public int indexOfValue(boolean value) {
218 for (int i = 0; i < mSize; i++)
219 if (mValues[i] == value)
220 return i;
221
222 return -1;
223 }
224
225 /**
226 * Removes all key-value mappings from this SparseBooleanArray.
227 */
228 public void clear() {
229 mSize = 0;
230 }
231
232 /**
233 * Puts a key/value pair into the array, optimizing for the case where
234 * the key is greater than all existing keys in the array.
235 */
236 public void append(int key, boolean value) {
237 if (mSize != 0 && key <= mKeys[mSize - 1]) {
238 put(key, value);
239 return;
240 }
241
Adam Lesinski776abc22014-03-07 11:30:59 -0500242 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
243 mValues = GrowingArrayUtils.append(mValues, mSize, value);
244 mSize++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700246
Steve McKay3b409d02015-07-22 11:42:14 -0700247 @Override
248 public int hashCode() {
249 int hashCode = mSize;
250 for (int i = 0; i < mSize; i++) {
251 hashCode = 31 * hashCode + mKeys[i] | (mValues[i] ? 1 : 0);
252 }
253 return hashCode;
254 }
255
256 @Override
257 public boolean equals(Object that) {
258 if (this == that) {
259 return true;
260 }
261
262 if (!(that instanceof SparseBooleanArray)) {
263 return false;
264 }
265
266 SparseBooleanArray other = (SparseBooleanArray) that;
267 if (mSize != other.mSize) {
268 return false;
269 }
270
271 for (int i = 0; i < mSize; i++) {
272 if (mKeys[i] != other.mKeys[i]) {
273 return false;
274 }
275 if (mValues[i] != other.mValues[i]) {
276 return false;
277 }
278 }
279 return true;
280 }
281
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700282 /**
283 * {@inheritDoc}
284 *
285 * <p>This implementation composes a string by iterating over its mappings.
286 */
287 @Override
288 public String toString() {
289 if (size() <= 0) {
290 return "{}";
291 }
292
293 StringBuilder buffer = new StringBuilder(mSize * 28);
294 buffer.append('{');
295 for (int i=0; i<mSize; i++) {
296 if (i > 0) {
297 buffer.append(", ");
298 }
299 int key = keyAt(i);
300 buffer.append(key);
301 buffer.append('=');
302 boolean value = valueAt(i);
303 buffer.append(value);
304 }
305 buffer.append('}');
306 return buffer.toString();
307 }
308
Jake Whartona8a04352018-09-29 01:52:24 -0400309 @UnsupportedAppUsage(maxTargetSdk = 28) // Use keyAt(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 private int[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -0400311 @UnsupportedAppUsage(maxTargetSdk = 28) // Use valueAt(int), setValueAt(int, boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 private boolean[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -0400313 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 private int mSize;
315}