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