blob: f167f009a942e2a8ba5c1b461bf186ef9855780b [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
Kweku Adams17d453e2019-03-05 15:30:42 -080019import android.annotation.UnsupportedAppUsage;
20
Jeff Sharkeydda73b52013-01-18 16:56:49 -080021import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050022import com.android.internal.util.GrowingArrayUtils;
23
24import libcore.util.EmptyArray;
Jeff Sharkeydda73b52013-01-18 16:56:49 -080025
Jeff Sharkeydda73b52013-01-18 16:56:49 -080026/**
27 * Map of {@code long} to {@code long}. Unlike a normal array of longs, there
Dianne Hackbornb993f412013-07-12 17:46:45 -070028 * can be gaps in the indices. It is intended to be more memory efficient than using a
29 * {@code HashMap}, 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>
Jeff Sharkeydda73b52013-01-18 16:56:49 -080040 *
Flavio Lerda57713022013-09-08 18:04:58 +010041 * <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
Newton Allenebb47952013-11-21 13:27:10 -080045 * order in the case of <code>valueAt(int)</code>.</p>
Flavio Lerda57713022013-09-08 18:04:58 +010046 *
Jeff Sharkeydda73b52013-01-18 16:56:49 -080047 * @hide
48 */
49public class LongSparseLongArray implements Cloneable {
Jake Whartona8a04352018-09-29 01:52:24 -040050 @UnsupportedAppUsage(maxTargetSdk = 28) // The type isn't even public.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080051 private long[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -040052 @UnsupportedAppUsage(maxTargetSdk = 28) // The type isn't even public.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080053 private long[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -040054 @UnsupportedAppUsage(maxTargetSdk = 28) // The type isn't even public.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080055 private int mSize;
56
57 /**
58 * Creates a new SparseLongArray containing no mappings.
59 */
60 public LongSparseLongArray() {
61 this(10);
62 }
63
64 /**
65 * Creates a new SparseLongArray containing no mappings that will not
66 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070067 * number of mappings. If you supply an initial capacity of 0, the
68 * sparse array will be initialized with a light-weight representation
69 * not requiring any additional array allocations.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080070 */
71 public LongSparseLongArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070072 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050073 mKeys = EmptyArray.LONG;
74 mValues = EmptyArray.LONG;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070075 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050076 mKeys = ArrayUtils.newUnpaddedLongArray(initialCapacity);
77 mValues = new long[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070078 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -080079 mSize = 0;
80 }
81
82 @Override
83 public LongSparseLongArray clone() {
84 LongSparseLongArray clone = null;
85 try {
86 clone = (LongSparseLongArray) super.clone();
87 clone.mKeys = mKeys.clone();
88 clone.mValues = mValues.clone();
89 } catch (CloneNotSupportedException cnse) {
90 /* ignore */
91 }
92 return clone;
93 }
94
95 /**
96 * Gets the long mapped from the specified key, or <code>0</code>
97 * if no such mapping has been made.
98 */
99 public long get(long key) {
100 return get(key, 0);
101 }
102
103 /**
104 * Gets the long mapped from the specified key, or the specified value
105 * if no such mapping has been made.
106 */
107 public long get(long key, long valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700108 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800109
110 if (i < 0) {
111 return valueIfKeyNotFound;
112 } else {
113 return mValues[i];
114 }
115 }
116
117 /**
118 * Removes the mapping from the specified key, if there was any.
119 */
120 public void delete(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700121 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800122
123 if (i >= 0) {
124 removeAt(i);
125 }
126 }
127
128 /**
129 * Removes the mapping at the given index.
130 */
131 public void removeAt(int index) {
132 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
133 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
134 mSize--;
135 }
136
137 /**
138 * Adds a mapping from the specified key to the specified value,
139 * replacing the previous mapping from the specified key if there
140 * was one.
141 */
142 public void put(long key, long value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700143 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800144
145 if (i >= 0) {
146 mValues[i] = value;
147 } else {
148 i = ~i;
149
Adam Lesinski776abc22014-03-07 11:30:59 -0500150 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
151 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800152 mSize++;
153 }
154 }
155
156 /**
157 * Returns the number of key-value mappings that this SparseIntArray
158 * currently stores.
159 */
160 public int size() {
161 return mSize;
162 }
163
164 /**
165 * Given an index in the range <code>0...size()-1</code>, returns
166 * the key from the <code>index</code>th key-value mapping that this
167 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100168 *
169 * <p>The keys corresponding to indices in ascending order are guaranteed to
170 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
171 * smallest key and <code>keyAt(size()-1)</code> will return the largest
172 * key.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800173 */
174 public long keyAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800175 if (index >= mSize) {
176 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
177 throw new ArrayIndexOutOfBoundsException(index);
178 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800179 return mKeys[index];
180 }
181
182 /**
183 * Given an index in the range <code>0...size()-1</code>, returns
184 * the value from the <code>index</code>th key-value mapping that this
185 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100186 *
187 * <p>The values corresponding to indices in ascending order are guaranteed
188 * to be associated with keys in ascending order, e.g.,
189 * <code>valueAt(0)</code> will return the value associated with the
190 * smallest key and <code>valueAt(size()-1)</code> will return the value
191 * associated with the largest key.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800192 */
193 public long valueAt(int index) {
Kweku Adams17d453e2019-03-05 15:30:42 -0800194 if (index >= mSize) {
195 // The array might be slightly bigger than mSize, in which case, indexing won't fail.
196 throw new ArrayIndexOutOfBoundsException(index);
197 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800198 return mValues[index];
199 }
200
201 /**
202 * Returns the index for which {@link #keyAt} would return the
203 * specified key, or a negative number if the specified
204 * key is not mapped.
205 */
206 public int indexOfKey(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700207 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800208 }
209
210 /**
211 * Returns an index for which {@link #valueAt} would return the
212 * specified key, or a negative number if no keys map to the
213 * specified value.
214 * Beware that this is a linear search, unlike lookups by key,
215 * and that multiple keys can map to the same value and this will
216 * find only one of them.
217 */
218 public int indexOfValue(long value) {
219 for (int i = 0; i < mSize; i++)
220 if (mValues[i] == value)
221 return i;
222
223 return -1;
224 }
225
226 /**
227 * Removes all key-value mappings from this SparseIntArray.
228 */
229 public void clear() {
230 mSize = 0;
231 }
232
233 /**
234 * Puts a key/value pair into the array, optimizing for the case where
235 * the key is greater than all existing keys in the array.
236 */
237 public void append(long key, long value) {
238 if (mSize != 0 && key <= mKeys[mSize - 1]) {
239 put(key, value);
240 return;
241 }
242
Adam Lesinski776abc22014-03-07 11:30:59 -0500243 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
244 mValues = GrowingArrayUtils.append(mValues, mSize, value);
245 mSize++;
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800246 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700247
248 /**
249 * {@inheritDoc}
250 *
251 * <p>This implementation composes a string by iterating over its mappings.
252 */
253 @Override
254 public String toString() {
255 if (size() <= 0) {
256 return "{}";
257 }
258
259 StringBuilder buffer = new StringBuilder(mSize * 28);
260 buffer.append('{');
261 for (int i=0; i<mSize; i++) {
262 if (i > 0) {
263 buffer.append(", ");
264 }
265 long key = keyAt(i);
266 buffer.append(key);
267 buffer.append('=');
268 long value = valueAt(i);
269 buffer.append(value);
270 }
271 buffer.append('}');
272 return buffer.toString();
273 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800274}