blob: af163ac8f24663dcc20798f780e5035d54849c7f [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;
Adam Lesinski776abc22014-03-07 11:30:59 -050020import com.android.internal.util.GrowingArrayUtils;
21
Mathew Inwood4eb56ab2018-08-14 17:24:32 +010022import android.annotation.UnsupportedAppUsage;
Adam Lesinski776abc22014-03-07 11:30:59 -050023import libcore.util.EmptyArray;
Jeff Sharkeydda73b52013-01-18 16:56:49 -080024
Jeff Sharkeydda73b52013-01-18 16:56:49 -080025/**
26 * Map of {@code long} to {@code long}. Unlike a normal array of longs, there
Dianne Hackbornb993f412013-07-12 17:46:45 -070027 * can be gaps in the indices. It is intended to be more memory efficient than using a
28 * {@code HashMap}, both because it avoids
29 * auto-boxing keys and values and its data structure doesn't rely on an extra entry object
30 * for each mapping.
31 *
32 * <p>Note that this container keeps its mappings in an array data structure,
33 * using a binary search to find keys. The implementation is not intended to be appropriate for
34 * data structures
35 * that may contain large numbers of items. It is generally slower than a traditional
36 * HashMap, since lookups require a binary search and adds and removes require inserting
37 * and deleting entries in the array. For containers holding up to hundreds of items,
38 * the performance difference is not significant, less than 50%.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -080039 *
Flavio Lerda57713022013-09-08 18:04:58 +010040 * <p>It is possible to iterate over the items in this container using
41 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
42 * <code>keyAt(int)</code> with ascending values of the index will return the
43 * keys in ascending order, or the values corresponding to the keys in ascending
Newton Allenebb47952013-11-21 13:27:10 -080044 * order in the case of <code>valueAt(int)</code>.</p>
Flavio Lerda57713022013-09-08 18:04:58 +010045 *
Jeff Sharkeydda73b52013-01-18 16:56:49 -080046 * @hide
47 */
48public class LongSparseLongArray implements Cloneable {
Jake Whartona8a04352018-09-29 01:52:24 -040049 @UnsupportedAppUsage(maxTargetSdk = 28) // The type isn't even public.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080050 private long[] mKeys;
Jake Whartona8a04352018-09-29 01:52:24 -040051 @UnsupportedAppUsage(maxTargetSdk = 28) // The type isn't even public.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080052 private long[] mValues;
Jake Whartona8a04352018-09-29 01:52:24 -040053 @UnsupportedAppUsage(maxTargetSdk = 28) // The type isn't even public.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080054 private int mSize;
55
56 /**
57 * Creates a new SparseLongArray containing no mappings.
58 */
59 public LongSparseLongArray() {
60 this(10);
61 }
62
63 /**
64 * Creates a new SparseLongArray containing no mappings that will not
65 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070066 * number of mappings. If you supply an initial capacity of 0, the
67 * sparse array will be initialized with a light-weight representation
68 * not requiring any additional array allocations.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080069 */
70 public LongSparseLongArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070071 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050072 mKeys = EmptyArray.LONG;
73 mValues = EmptyArray.LONG;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070074 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050075 mKeys = ArrayUtils.newUnpaddedLongArray(initialCapacity);
76 mValues = new long[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070077 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -080078 mSize = 0;
79 }
80
81 @Override
82 public LongSparseLongArray clone() {
83 LongSparseLongArray clone = null;
84 try {
85 clone = (LongSparseLongArray) super.clone();
86 clone.mKeys = mKeys.clone();
87 clone.mValues = mValues.clone();
88 } catch (CloneNotSupportedException cnse) {
89 /* ignore */
90 }
91 return clone;
92 }
93
94 /**
95 * Gets the long mapped from the specified key, or <code>0</code>
96 * if no such mapping has been made.
97 */
98 public long get(long key) {
99 return get(key, 0);
100 }
101
102 /**
103 * Gets the long mapped from the specified key, or the specified value
104 * if no such mapping has been made.
105 */
106 public long get(long key, long valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700107 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800108
109 if (i < 0) {
110 return valueIfKeyNotFound;
111 } else {
112 return mValues[i];
113 }
114 }
115
116 /**
117 * Removes the mapping from the specified key, if there was any.
118 */
119 public void delete(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700120 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800121
122 if (i >= 0) {
123 removeAt(i);
124 }
125 }
126
127 /**
128 * Removes the mapping at the given index.
129 */
130 public void removeAt(int index) {
131 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
132 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
133 mSize--;
134 }
135
136 /**
137 * Adds a mapping from the specified key to the specified value,
138 * replacing the previous mapping from the specified key if there
139 * was one.
140 */
141 public void put(long key, long value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700142 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800143
144 if (i >= 0) {
145 mValues[i] = value;
146 } else {
147 i = ~i;
148
Adam Lesinski776abc22014-03-07 11:30:59 -0500149 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
150 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800151 mSize++;
152 }
153 }
154
155 /**
156 * Returns the number of key-value mappings that this SparseIntArray
157 * currently stores.
158 */
159 public int size() {
160 return mSize;
161 }
162
163 /**
164 * Given an index in the range <code>0...size()-1</code>, returns
165 * the key from the <code>index</code>th key-value mapping that this
166 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100167 *
168 * <p>The keys corresponding to indices in ascending order are guaranteed to
169 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
170 * smallest key and <code>keyAt(size()-1)</code> will return the largest
171 * key.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800172 */
173 public long keyAt(int index) {
174 return mKeys[index];
175 }
176
177 /**
178 * Given an index in the range <code>0...size()-1</code>, returns
179 * the value from the <code>index</code>th key-value mapping that this
180 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100181 *
182 * <p>The values corresponding to indices in ascending order are guaranteed
183 * to be associated with keys in ascending order, e.g.,
184 * <code>valueAt(0)</code> will return the value associated with the
185 * smallest key and <code>valueAt(size()-1)</code> will return the value
186 * associated with the largest key.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800187 */
188 public long valueAt(int index) {
189 return mValues[index];
190 }
191
192 /**
193 * Returns the index for which {@link #keyAt} would return the
194 * specified key, or a negative number if the specified
195 * key is not mapped.
196 */
197 public int indexOfKey(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700198 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800199 }
200
201 /**
202 * Returns an index for which {@link #valueAt} would return the
203 * specified key, or a negative number if no keys map to the
204 * specified value.
205 * Beware that this is a linear search, unlike lookups by key,
206 * and that multiple keys can map to the same value and this will
207 * find only one of them.
208 */
209 public int indexOfValue(long value) {
210 for (int i = 0; i < mSize; i++)
211 if (mValues[i] == value)
212 return i;
213
214 return -1;
215 }
216
217 /**
218 * Removes all key-value mappings from this SparseIntArray.
219 */
220 public void clear() {
221 mSize = 0;
222 }
223
224 /**
225 * Puts a key/value pair into the array, optimizing for the case where
226 * the key is greater than all existing keys in the array.
227 */
228 public void append(long key, long value) {
229 if (mSize != 0 && key <= mKeys[mSize - 1]) {
230 put(key, value);
231 return;
232 }
233
Adam Lesinski776abc22014-03-07 11:30:59 -0500234 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
235 mValues = GrowingArrayUtils.append(mValues, mSize, value);
236 mSize++;
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800237 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700238
239 /**
240 * {@inheritDoc}
241 *
242 * <p>This implementation composes a string by iterating over its mappings.
243 */
244 @Override
245 public String toString() {
246 if (size() <= 0) {
247 return "{}";
248 }
249
250 StringBuilder buffer = new StringBuilder(mSize * 28);
251 buffer.append('{');
252 for (int i=0; i<mSize; i++) {
253 if (i > 0) {
254 buffer.append(", ");
255 }
256 long key = keyAt(i);
257 buffer.append(key);
258 buffer.append('=');
259 long value = valueAt(i);
260 buffer.append(value);
261 }
262 buffer.append('}');
263 return buffer.toString();
264 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800265}