• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 com.android.internal.util.ArrayUtils;
20 import com.android.internal.util.GrowingArrayUtils;
21 
22 import libcore.util.EmptyArray;
23 
24 /**
25  * SparseLongArrays map integers to longs.  Unlike a normal array of longs,
26  * there can be gaps in the indices.  It is intended to be more memory efficient
27  * than using a HashMap to map Integers to Longs, 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>
38  *
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
43  * order in the case of <code>valueAt(int)</code>.</p>
44  */
45 public class SparseLongArray implements Cloneable {
46     private int[] mKeys;
47     private long[] mValues;
48     private int mSize;
49 
50     /**
51      * Creates a new SparseLongArray containing no mappings.
52      */
SparseLongArray()53     public SparseLongArray() {
54         this(0);
55     }
56 
57     /**
58      * Creates a new SparseLongArray containing no mappings that will not
59      * require any additional memory allocation to store the specified
60      * 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.
63      */
SparseLongArray(int initialCapacity)64     public SparseLongArray(int initialCapacity) {
65         if (initialCapacity == 0) {
66             mKeys = EmptyArray.INT;
67             mValues = EmptyArray.LONG;
68         } else {
69             mValues = ArrayUtils.newUnpaddedLongArray(initialCapacity);
70             mKeys = new int[mValues.length];
71         }
72         mSize = 0;
73     }
74 
75     @Override
clone()76     public SparseLongArray clone() {
77         SparseLongArray clone = null;
78         try {
79             clone = (SparseLongArray) super.clone();
80             clone.mKeys = mKeys.clone();
81             clone.mValues = mValues.clone();
82         } catch (CloneNotSupportedException cnse) {
83             /* ignore */
84         }
85         return clone;
86     }
87 
88     /**
89      * Gets the long mapped from the specified key, or <code>0</code>
90      * if no such mapping has been made.
91      */
get(int key)92     public long get(int key) {
93         return get(key, 0);
94     }
95 
96     /**
97      * Gets the long mapped from the specified key, or the specified value
98      * if no such mapping has been made.
99      */
get(int key, long valueIfKeyNotFound)100     public long get(int key, long valueIfKeyNotFound) {
101         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
102 
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      */
delete(int key)113     public void delete(int key) {
114         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
115 
116         if (i >= 0) {
117             removeAt(i);
118         }
119     }
120 
121     /**
122      * @hide
123      * Remove a range of mappings as a batch.
124      *
125      * @param index Index to begin at
126      * @param size Number of mappings to remove
127      *
128      * <p>For indices outside of the range <code>0...size()-1</code>,
129      * the behavior is undefined.</p>
130      */
removeAtRange(int index, int size)131     public void removeAtRange(int index, int size) {
132         size = Math.min(size, mSize - index);
133         System.arraycopy(mKeys, index + size, mKeys, index, mSize - (index + size));
134         System.arraycopy(mValues, index + size, mValues, index, mSize - (index + size));
135         mSize -= size;
136     }
137 
138     /**
139      * Removes the mapping at the given index.
140      */
removeAt(int index)141     public void removeAt(int index) {
142         System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
143         System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
144         mSize--;
145     }
146 
147     /**
148      * Adds a mapping from the specified key to the specified value,
149      * replacing the previous mapping from the specified key if there
150      * was one.
151      */
put(int key, long value)152     public void put(int key, long value) {
153         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
154 
155         if (i >= 0) {
156             mValues[i] = value;
157         } else {
158             i = ~i;
159 
160             mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
161             mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
162             mSize++;
163         }
164     }
165 
166     /**
167      * Adds a mapping from the specified key to the specified value,
168      * <b>adding</b> its value to the previous mapping from the specified key if there
169      * was one.
170      *
171      * <p>This differs from {@link #put} because instead of replacing any previous value, it adds
172      * (in the numerical sense) to it.
173      *
174      * @hide
175      */
incrementValue(int key, long summand)176     public void incrementValue(int key, long summand) {
177         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
178 
179         if (i >= 0) {
180             mValues[i] += summand;
181         } else {
182             i = ~i;
183 
184             mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
185             mValues = GrowingArrayUtils.insert(mValues, mSize, i, summand);
186             mSize++;
187         }
188     }
189 
190     /**
191      * Returns the number of key-value mappings that this SparseLongArray
192      * currently stores.
193      */
size()194     public int size() {
195         return mSize;
196     }
197 
198     /**
199      * Given an index in the range <code>0...size()-1</code>, returns
200      * the key from the <code>index</code>th key-value mapping that this
201      * SparseLongArray stores.
202      *
203      * <p>The keys corresponding to indices in ascending order are guaranteed to
204      * be in ascending order, e.g., <code>keyAt(0)</code> will return the
205      * smallest key and <code>keyAt(size()-1)</code> will return the largest
206      * key.</p>
207      *
208      * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
209      * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
210      * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
211      * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
212      */
keyAt(int index)213     public int keyAt(int index) {
214         if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
215             // The array might be slightly bigger than mSize, in which case, indexing won't fail.
216             // Check if exception should be thrown outside of the critical path.
217             throw new ArrayIndexOutOfBoundsException(index);
218         }
219         return mKeys[index];
220     }
221 
222     /**
223      * Given an index in the range <code>0...size()-1</code>, returns
224      * the value from the <code>index</code>th key-value mapping that this
225      * SparseLongArray stores.
226      *
227      * <p>The values corresponding to indices in ascending order are guaranteed
228      * to be associated with keys in ascending order, e.g.,
229      * <code>valueAt(0)</code> will return the value associated with the
230      * smallest key and <code>valueAt(size()-1)</code> will return the value
231      * associated with the largest key.</p>
232      *
233      * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
234      * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
235      * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
236      * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
237      */
valueAt(int index)238     public long valueAt(int index) {
239         if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
240             // The array might be slightly bigger than mSize, in which case, indexing won't fail.
241             // Check if exception should be thrown outside of the critical path.
242             throw new ArrayIndexOutOfBoundsException(index);
243         }
244         return mValues[index];
245     }
246 
247     /**
248      * Given an index in the range <code>0...size()-1</code>, sets a new
249      * value for the <code>index</code>th key-value mapping that this
250      * SparseLongArray stores.
251      *
252      * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for
253      * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an
254      * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting
255      * {@link android.os.Build.VERSION_CODES#Q} and later.</p>
256      *
257      * @hide
258      */
setValueAt(int index, long value)259     public void setValueAt(int index, long value) {
260         if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
261             // The array might be slightly bigger than mSize, in which case, indexing won't fail.
262             // Check if exception should be thrown outside of the critical path.
263             throw new ArrayIndexOutOfBoundsException(index);
264         }
265 
266         mValues[index] = value;
267     }
268 
269     /**
270      * Returns the index for which {@link #keyAt} would return the
271      * specified key, or a negative number if the specified
272      * key is not mapped.
273      */
indexOfKey(int key)274     public int indexOfKey(int key) {
275         return ContainerHelpers.binarySearch(mKeys, mSize, key);
276     }
277 
278     /**
279      * Returns an index for which {@link #valueAt} would return the
280      * specified key, or a negative number if no keys map to the
281      * specified value.
282      * Beware that this is a linear search, unlike lookups by key,
283      * and that multiple keys can map to the same value and this will
284      * find only one of them.
285      */
indexOfValue(long value)286     public int indexOfValue(long value) {
287         for (int i = 0; i < mSize; i++)
288             if (mValues[i] == value)
289                 return i;
290 
291         return -1;
292     }
293 
294     /**
295      * Removes all key-value mappings from this SparseLongArray.
296      */
clear()297     public void clear() {
298         mSize = 0;
299     }
300 
301     /**
302      * Puts a key/value pair into the array, optimizing for the case where
303      * the key is greater than all existing keys in the array.
304      */
append(int key, long value)305     public void append(int key, long value) {
306         if (mSize != 0 && key <= mKeys[mSize - 1]) {
307             put(key, value);
308             return;
309         }
310 
311         mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
312         mValues = GrowingArrayUtils.append(mValues, mSize, value);
313         mSize++;
314     }
315 
316     /**
317      * {@inheritDoc}
318      *
319      * <p>This implementation composes a string by iterating over its mappings.
320      */
321     @Override
toString()322     public String toString() {
323         if (size() <= 0) {
324             return "{}";
325         }
326 
327         StringBuilder buffer = new StringBuilder(mSize * 28);
328         buffer.append('{');
329         for (int i=0; i<mSize; i++) {
330             if (i > 0) {
331                 buffer.append(", ");
332             }
333             int key = keyAt(i);
334             buffer.append(key);
335             buffer.append('=');
336             long value = valueAt(i);
337             buffer.append(value);
338         }
339         buffer.append('}');
340         return buffer.toString();
341     }
342 }
343