blob: 182fd35c4fbedb79c09d09f974a831af3f9c956f [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;
20
21/**
22 * SparseLongArrays map integers to longs. Unlike a normal array of longs,
Dianne Hackbornb993f412013-07-12 17:46:45 -070023 * there can be gaps in the indices. It is intended to be more memory efficient
24 * than using a HashMap to map Integers to Longs, both because it avoids
25 * auto-boxing keys and values and its data structure doesn't rely on an extra entry object
26 * for each mapping.
27 *
28 * <p>Note that this container keeps its mappings in an array data structure,
29 * using a binary search to find keys. The implementation is not intended to be appropriate for
30 * data structures
31 * that may contain large numbers of items. It is generally slower than a traditional
32 * HashMap, since lookups require a binary search and adds and removes require inserting
33 * and deleting entries in the array. For containers holding up to hundreds of items,
34 * the performance difference is not significant, less than 50%.</p>
Svetoslav Ganov02107852011-10-03 17:06:56 -070035 */
36public class SparseLongArray implements Cloneable {
Svetoslav Ganov02107852011-10-03 17:06:56 -070037 private int[] mKeys;
38 private long[] mValues;
39 private int mSize;
40
41 /**
42 * Creates a new SparseLongArray containing no mappings.
43 */
44 public SparseLongArray() {
45 this(10);
46 }
47
48 /**
49 * Creates a new SparseLongArray containing no mappings that will not
50 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070051 * number of mappings. If you supply an initial capacity of 0, the
52 * sparse array will be initialized with a light-weight representation
53 * not requiring any additional array allocations.
Svetoslav Ganov02107852011-10-03 17:06:56 -070054 */
55 public SparseLongArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070056 if (initialCapacity == 0) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070057 mKeys = ContainerHelpers.EMPTY_INTS;
58 mValues = ContainerHelpers.EMPTY_LONGS;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070059 } else {
60 initialCapacity = ArrayUtils.idealLongArraySize(initialCapacity);
61 mKeys = new int[initialCapacity];
62 mValues = new long[initialCapacity];
63 }
Svetoslav Ganov02107852011-10-03 17:06:56 -070064 mSize = 0;
65 }
66
67 @Override
68 public SparseLongArray clone() {
69 SparseLongArray clone = null;
70 try {
71 clone = (SparseLongArray) super.clone();
72 clone.mKeys = mKeys.clone();
73 clone.mValues = mValues.clone();
74 } catch (CloneNotSupportedException cnse) {
75 /* ignore */
76 }
77 return clone;
78 }
79
80 /**
81 * Gets the long mapped from the specified key, or <code>0</code>
82 * if no such mapping has been made.
83 */
84 public long get(int key) {
85 return get(key, 0);
86 }
87
88 /**
89 * Gets the long mapped from the specified key, or the specified value
90 * if no such mapping has been made.
91 */
92 public long get(int key, long valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070093 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -070094
95 if (i < 0) {
96 return valueIfKeyNotFound;
97 } else {
98 return mValues[i];
99 }
100 }
101
102 /**
103 * Removes the mapping from the specified key, if there was any.
104 */
105 public void delete(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700106 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700107
108 if (i >= 0) {
109 removeAt(i);
110 }
111 }
112
113 /**
114 * Removes the mapping at the given index.
115 */
116 public void removeAt(int index) {
117 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
118 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
119 mSize--;
120 }
121
122 /**
123 * Adds a mapping from the specified key to the specified value,
124 * replacing the previous mapping from the specified key if there
125 * was one.
126 */
127 public void put(int key, long value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700128 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700129
130 if (i >= 0) {
131 mValues[i] = value;
132 } else {
133 i = ~i;
134
135 if (mSize >= mKeys.length) {
136 growKeyAndValueArrays(mSize + 1);
137 }
138
139 if (mSize - i != 0) {
140 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
141 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
142 }
143
144 mKeys[i] = key;
145 mValues[i] = value;
146 mSize++;
147 }
148 }
149
150 /**
151 * Returns the number of key-value mappings that this SparseIntArray
152 * currently stores.
153 */
154 public int size() {
155 return mSize;
156 }
157
158 /**
159 * Given an index in the range <code>0...size()-1</code>, returns
160 * the key from the <code>index</code>th key-value mapping that this
161 * SparseLongArray stores.
162 */
163 public int keyAt(int index) {
164 return mKeys[index];
165 }
166
167 /**
168 * Given an index in the range <code>0...size()-1</code>, returns
169 * the value from the <code>index</code>th key-value mapping that this
170 * SparseLongArray stores.
171 */
172 public long valueAt(int index) {
173 return mValues[index];
174 }
175
176 /**
177 * Returns the index for which {@link #keyAt} would return the
178 * specified key, or a negative number if the specified
179 * key is not mapped.
180 */
181 public int indexOfKey(int key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700182 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Svetoslav Ganov02107852011-10-03 17:06:56 -0700183 }
184
185 /**
186 * Returns an index for which {@link #valueAt} would return the
187 * specified key, or a negative number if no keys map to the
188 * specified value.
189 * Beware that this is a linear search, unlike lookups by key,
190 * and that multiple keys can map to the same value and this will
191 * find only one of them.
192 */
193 public int indexOfValue(long value) {
194 for (int i = 0; i < mSize; i++)
195 if (mValues[i] == value)
196 return i;
197
198 return -1;
199 }
200
201 /**
202 * Removes all key-value mappings from this SparseIntArray.
203 */
204 public void clear() {
205 mSize = 0;
206 }
207
208 /**
209 * Puts a key/value pair into the array, optimizing for the case where
210 * the key is greater than all existing keys in the array.
211 */
212 public void append(int key, long value) {
213 if (mSize != 0 && key <= mKeys[mSize - 1]) {
214 put(key, value);
215 return;
216 }
217
218 int pos = mSize;
219 if (pos >= mKeys.length) {
220 growKeyAndValueArrays(pos + 1);
221 }
222
223 mKeys[pos] = key;
224 mValues[pos] = value;
225 mSize = pos + 1;
226 }
227
228 private void growKeyAndValueArrays(int minNeededSize) {
229 int n = ArrayUtils.idealLongArraySize(minNeededSize);
230
231 int[] nkeys = new int[n];
232 long[] nvalues = new long[n];
233
234 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
235 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
236
237 mKeys = nkeys;
238 mValues = nvalues;
239 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700240
241 /**
242 * {@inheritDoc}
243 *
244 * <p>This implementation composes a string by iterating over its mappings.
245 */
246 @Override
247 public String toString() {
248 if (size() <= 0) {
249 return "{}";
250 }
251
252 StringBuilder buffer = new StringBuilder(mSize * 28);
253 buffer.append('{');
254 for (int i=0; i<mSize; i++) {
255 if (i > 0) {
256 buffer.append(", ");
257 }
258 int key = keyAt(i);
259 buffer.append(key);
260 buffer.append('=');
261 long value = valueAt(i);
262 buffer.append(value);
263 }
264 buffer.append('}');
265 return buffer.toString();
266 }
Svetoslav Ganov02107852011-10-03 17:06:56 -0700267}