blob: 81db2b7ff715375491804663928eccbab88516f4 [file] [log] [blame]
Svetoslav Ganov02107852011-10-03 17:06:56 -07001/*
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
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;
Svetoslav Ganov02107852011-10-03 17:06:56 -070023
24/**
25 * SparseLongArrays map integers to longs. Unlike a normal array of longs,
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 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>
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>
Svetoslav Ganov02107852011-10-03 17:06:56 -070044 */
45public class SparseLongArray implements Cloneable {
Svetoslav Ganov02107852011-10-03 17:06:56 -070046 private int[] mKeys;
47 private long[] mValues;
48 private int mSize;
49
50 /**
51 * Creates a new SparseLongArray containing no mappings.
52 */
53 public SparseLongArray() {
54 this(10);
55 }
56
57 /**
58 * Creates a new SparseLongArray 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.
Svetoslav Ganov02107852011-10-03 17:06:56 -070063 */
64 public SparseLongArray(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.LONG;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070068 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050069 mValues = ArrayUtils.newUnpaddedLongArray(initialCapacity);
70 mKeys = new int[mValues.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070071 }
Svetoslav Ganov02107852011-10-03 17:06:56 -070072 mSize = 0;
73 }
74
75 @Override
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 */
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 */
100 public long get(int key, long valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700101 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700102
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);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700115
116 if (i >= 0) {
117 removeAt(i);
118 }
119 }
120
121 /**
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700122 * @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 */
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 /**
Svetoslav Ganov02107852011-10-03 17:06:56 -0700139 * Removes the mapping at the given index.
140 */
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 */
152 public void put(int key, long value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700153 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700154
155 if (i >= 0) {
156 mValues[i] = value;
157 } else {
158 i = ~i;
159
Adam Lesinski776abc22014-03-07 11:30:59 -0500160 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
161 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700162 mSize++;
163 }
164 }
165
166 /**
167 * Returns the number of key-value mappings that this SparseIntArray
168 * currently stores.
169 */
170 public int size() {
171 return mSize;
172 }
173
174 /**
175 * Given an index in the range <code>0...size()-1</code>, returns
176 * the key from the <code>index</code>th key-value mapping that this
177 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100178 *
179 * <p>The keys corresponding to indices in ascending order are guaranteed to
180 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
181 * smallest key and <code>keyAt(size()-1)</code> will return the largest
182 * key.</p>
Svetoslav Ganov02107852011-10-03 17:06:56 -0700183 */
184 public int keyAt(int index) {
185 return mKeys[index];
186 }
187
188 /**
189 * Given an index in the range <code>0...size()-1</code>, returns
190 * the value from the <code>index</code>th key-value mapping that this
191 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100192 *
193 * <p>The values corresponding to indices in ascending order are guaranteed
194 * to be associated with keys in ascending order, e.g.,
195 * <code>valueAt(0)</code> will return the value associated with the
196 * smallest key and <code>valueAt(size()-1)</code> will return the value
197 * associated with the largest key.</p>
Svetoslav Ganov02107852011-10-03 17:06:56 -0700198 */
199 public long valueAt(int index) {
200 return mValues[index];
201 }
202
203 /**
204 * Returns the index for which {@link #keyAt} would return the
205 * specified key, or a negative number if the specified
206 * key is not mapped.
207 */
208 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700209 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700210 }
211
212 /**
213 * Returns an index for which {@link #valueAt} would return the
214 * specified key, or a negative number if no keys map to the
215 * specified value.
216 * Beware that this is a linear search, unlike lookups by key,
217 * and that multiple keys can map to the same value and this will
218 * find only one of them.
219 */
220 public int indexOfValue(long value) {
221 for (int i = 0; i < mSize; i++)
222 if (mValues[i] == value)
223 return i;
224
225 return -1;
226 }
227
228 /**
229 * Removes all key-value mappings from this SparseIntArray.
230 */
231 public void clear() {
232 mSize = 0;
233 }
234
235 /**
236 * Puts a key/value pair into the array, optimizing for the case where
237 * the key is greater than all existing keys in the array.
238 */
239 public void append(int key, long value) {
240 if (mSize != 0 && key <= mKeys[mSize - 1]) {
241 put(key, value);
242 return;
243 }
244
Adam Lesinski776abc22014-03-07 11:30:59 -0500245 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
246 mValues = GrowingArrayUtils.append(mValues, mSize, value);
247 mSize++;
Svetoslav Ganov02107852011-10-03 17:06:56 -0700248 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700249
250 /**
251 * {@inheritDoc}
252 *
253 * <p>This implementation composes a string by iterating over its mappings.
254 */
255 @Override
256 public String toString() {
257 if (size() <= 0) {
258 return "{}";
259 }
260
261 StringBuilder buffer = new StringBuilder(mSize * 28);
262 buffer.append('{');
263 for (int i=0; i<mSize; i++) {
264 if (i > 0) {
265 buffer.append(", ");
266 }
267 int key = keyAt(i);
268 buffer.append(key);
269 buffer.append('=');
270 long value = valueAt(i);
271 buffer.append(value);
272 }
273 buffer.append('}');
274 return buffer.toString();
275 }
Svetoslav Ganov02107852011-10-03 17:06:56 -0700276}