1 /* 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 17 package android.util; 18 19 import android.compat.annotation.UnsupportedAppUsage; 20 21 import com.android.internal.util.ArrayUtils; 22 import com.android.internal.util.GrowingArrayUtils; 23 24 import java.util.Arrays; 25 26 /** 27 * SparseIntArrays map integers to integers. Unlike a normal array of integers, 28 * there can be gaps in the indices. It is intended to be more memory efficient 29 * than using a HashMap to map Integers to Integers, 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> 40 * 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 45 * order in the case of <code>valueAt(int)</code>.</p> 46 */ 47 @android.ravenwood.annotation.RavenwoodKeepWholeClass 48 public class SparseIntArray implements Cloneable { 49 @UnsupportedAppUsage(maxTargetSdk = 28) // Use keyAt(int) 50 private int[] mKeys; 51 @UnsupportedAppUsage(maxTargetSdk = 28) // Use valueAt(int), setValueAt(int, int) 52 private int[] mValues; 53 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size() 54 private int mSize; 55 56 /** 57 * Creates a new SparseIntArray containing no mappings. 58 */ SparseIntArray()59 public SparseIntArray() { 60 this(0); 61 } 62 63 /** 64 * Creates a new SparseIntArray containing no mappings that will not 65 * require any additional memory allocation to store the specified 66 * 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. 69 */ SparseIntArray(int initialCapacity)70 public SparseIntArray(int initialCapacity) { 71 if (initialCapacity == 0) { 72 mKeys = EmptyArray.INT; 73 mValues = EmptyArray.INT; 74 } else { 75 mKeys = ArrayUtils.newUnpaddedIntArray(initialCapacity); 76 mValues = new int[mKeys.length]; 77 } 78 mSize = 0; 79 } 80 81 @Override clone()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 94 /** 95 * Gets the int mapped from the specified key, or <code>0</code> 96 * if no such mapping has been made. 97 */ get(int key)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 */ get(int key, int valueIfKeyNotFound)106 public int get(int key, int valueIfKeyNotFound) { 107 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 108 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 */ delete(int key)119 public void delete(int key) { 120 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 121 122 if (i >= 0) { 123 removeAt(i); 124 } 125 } 126 127 /** 128 * Removes the mapping at the given index. 129 */ removeAt(int index)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 */ put(int key, int value)141 public void put(int key, int value) { 142 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 143 144 if (i >= 0) { 145 mValues[i] = value; 146 } else { 147 i = ~i; 148 149 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key); 150 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value); 151 mSize++; 152 } 153 } 154 155 /** 156 * Returns the number of key-value mappings that this SparseIntArray 157 * currently stores. 158 */ size()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 166 * 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> 172 * 173 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for 174 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an 175 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting 176 * {@link android.os.Build.VERSION_CODES#Q} and later.</p> 177 */ keyAt(int index)178 public int keyAt(int index) { 179 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) { 180 // The array might be slightly bigger than mSize, in which case, indexing won't fail. 181 // Check if exception should be thrown outside of the critical path. 182 throw new ArrayIndexOutOfBoundsException(index); 183 } 184 return mKeys[index]; 185 } 186 187 /** 188 * Given an index in the range <code>0...size()-1</code>, returns 189 * the value from the <code>index</code>th key-value mapping that this 190 * SparseIntArray stores. 191 * 192 * <p>The values corresponding to indices in ascending order are guaranteed 193 * to be associated with keys in ascending order, e.g., 194 * <code>valueAt(0)</code> will return the value associated with the 195 * smallest key and <code>valueAt(size()-1)</code> will return the value 196 * associated with the largest key.</p> 197 * 198 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for 199 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an 200 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting 201 * {@link android.os.Build.VERSION_CODES#Q} and later.</p> 202 */ valueAt(int index)203 public int valueAt(int index) { 204 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) { 205 // The array might be slightly bigger than mSize, in which case, indexing won't fail. 206 // Check if exception should be thrown outside of the critical path. 207 throw new ArrayIndexOutOfBoundsException(index); 208 } 209 return mValues[index]; 210 } 211 212 /** 213 * Directly set the value at a particular index. 214 * 215 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for 216 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an 217 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting 218 * {@link android.os.Build.VERSION_CODES#Q} and later.</p> 219 */ setValueAt(int index, int value)220 public void setValueAt(int index, int value) { 221 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) { 222 // The array might be slightly bigger than mSize, in which case, indexing won't fail. 223 // Check if exception should be thrown outside of the critical path. 224 throw new ArrayIndexOutOfBoundsException(index); 225 } 226 mValues[index] = value; 227 } 228 229 /** 230 * Returns the index for which {@link #keyAt} would return the 231 * specified key, or a negative number if the specified 232 * key is not mapped. 233 */ indexOfKey(int key)234 public int indexOfKey(int key) { 235 return ContainerHelpers.binarySearch(mKeys, mSize, key); 236 } 237 238 /** 239 * Returns an index for which {@link #valueAt} would return the 240 * specified key, or a negative number if no keys map to the 241 * specified value. 242 * Beware that this is a linear search, unlike lookups by key, 243 * and that multiple keys can map to the same value and this will 244 * find only one of them. 245 */ indexOfValue(int value)246 public int indexOfValue(int value) { 247 for (int i = 0; i < mSize; i++) 248 if (mValues[i] == value) 249 return i; 250 251 return -1; 252 } 253 254 /** 255 * Removes all key-value mappings from this SparseIntArray. 256 */ clear()257 public void clear() { 258 mSize = 0; 259 } 260 261 /** 262 * Puts a key/value pair into the array, optimizing for the case where 263 * the key is greater than all existing keys in the array. 264 */ append(int key, int value)265 public void append(int key, int value) { 266 if (mSize != 0 && key <= mKeys[mSize - 1]) { 267 put(key, value); 268 return; 269 } 270 271 mKeys = GrowingArrayUtils.append(mKeys, mSize, key); 272 mValues = GrowingArrayUtils.append(mValues, mSize, value); 273 mSize++; 274 } 275 276 /** 277 * Provides a copy of keys. 278 * 279 * @hide 280 * */ copyKeys()281 public int[] copyKeys() { 282 if (size() == 0) { 283 return null; 284 } 285 return Arrays.copyOf(mKeys, size()); 286 } 287 288 /** 289 * {@inheritDoc} 290 * 291 * <p>This implementation composes a string by iterating over its mappings. 292 */ 293 @Override toString()294 public String toString() { 295 if (size() <= 0) { 296 return "{}"; 297 } 298 299 StringBuilder buffer = new StringBuilder(mSize * 28); 300 buffer.append('{'); 301 for (int i=0; i<mSize; i++) { 302 if (i > 0) { 303 buffer.append(", "); 304 } 305 int key = keyAt(i); 306 buffer.append(key); 307 buffer.append('='); 308 int value = valueAt(i); 309 buffer.append(value); 310 } 311 buffer.append('}'); 312 return buffer.toString(); 313 } 314 } 315