blob: a3614572c0f39799c709e13f596e34f569703215 [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
22import libcore.util.EmptyArray;
Jeff Sharkeydda73b52013-01-18 16:56:49 -080023
Jeff Sharkeydda73b52013-01-18 16:56:49 -080024/**
25 * Map of {@code long} to {@code long}. Unlike a normal array of longs, there
Dianne Hackbornb993f412013-07-12 17:46:45 -070026 * can be gaps in the indices. It is intended to be more memory efficient than using a
27 * {@code HashMap}, 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>
Jeff Sharkeydda73b52013-01-18 16:56:49 -080038 *
Flavio Lerda57713022013-09-08 18:04:58 +010039 * <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>
Flavio Lerda57713022013-09-08 18:04:58 +010044 *
Jeff Sharkeydda73b52013-01-18 16:56:49 -080045 * @hide
46 */
47public class LongSparseLongArray implements Cloneable {
48 private long[] mKeys;
49 private long[] mValues;
50 private int mSize;
51
52 /**
53 * Creates a new SparseLongArray containing no mappings.
54 */
55 public LongSparseLongArray() {
56 this(10);
57 }
58
59 /**
60 * Creates a new SparseLongArray containing no mappings that will not
61 * require any additional memory allocation to store the specified
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070062 * number of mappings. If you supply an initial capacity of 0, the
63 * sparse array will be initialized with a light-weight representation
64 * not requiring any additional array allocations.
Jeff Sharkeydda73b52013-01-18 16:56:49 -080065 */
66 public LongSparseLongArray(int initialCapacity) {
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070067 if (initialCapacity == 0) {
Adam Lesinski776abc22014-03-07 11:30:59 -050068 mKeys = EmptyArray.LONG;
69 mValues = EmptyArray.LONG;
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070070 } else {
Adam Lesinski776abc22014-03-07 11:30:59 -050071 mKeys = ArrayUtils.newUnpaddedLongArray(initialCapacity);
72 mValues = new long[mKeys.length];
Dianne Hackbornf4bf0ae2013-05-20 18:42:16 -070073 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -080074 mSize = 0;
75 }
76
77 @Override
78 public LongSparseLongArray clone() {
79 LongSparseLongArray clone = null;
80 try {
81 clone = (LongSparseLongArray) super.clone();
82 clone.mKeys = mKeys.clone();
83 clone.mValues = mValues.clone();
84 } catch (CloneNotSupportedException cnse) {
85 /* ignore */
86 }
87 return clone;
88 }
89
90 /**
91 * Gets the long mapped from the specified key, or <code>0</code>
92 * if no such mapping has been made.
93 */
94 public long get(long key) {
95 return get(key, 0);
96 }
97
98 /**
99 * Gets the long mapped from the specified key, or the specified value
100 * if no such mapping has been made.
101 */
102 public long get(long key, long valueIfKeyNotFound) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700103 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800104
105 if (i < 0) {
106 return valueIfKeyNotFound;
107 } else {
108 return mValues[i];
109 }
110 }
111
112 /**
113 * Removes the mapping from the specified key, if there was any.
114 */
115 public void delete(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700116 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800117
118 if (i >= 0) {
119 removeAt(i);
120 }
121 }
122
123 /**
124 * Removes the mapping at the given index.
125 */
126 public void removeAt(int index) {
127 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
128 System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
129 mSize--;
130 }
131
132 /**
133 * Adds a mapping from the specified key to the specified value,
134 * replacing the previous mapping from the specified key if there
135 * was one.
136 */
137 public void put(long key, long value) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700138 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800139
140 if (i >= 0) {
141 mValues[i] = value;
142 } else {
143 i = ~i;
144
Adam Lesinski776abc22014-03-07 11:30:59 -0500145 mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
146 mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800147 mSize++;
148 }
149 }
150
151 /**
152 * Returns the number of key-value mappings that this SparseIntArray
153 * currently stores.
154 */
155 public int size() {
156 return mSize;
157 }
158
159 /**
160 * Given an index in the range <code>0...size()-1</code>, returns
161 * the key from the <code>index</code>th key-value mapping that this
162 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100163 *
164 * <p>The keys corresponding to indices in ascending order are guaranteed to
165 * be in ascending order, e.g., <code>keyAt(0)</code> will return the
166 * smallest key and <code>keyAt(size()-1)</code> will return the largest
167 * key.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800168 */
169 public long keyAt(int index) {
170 return mKeys[index];
171 }
172
173 /**
174 * Given an index in the range <code>0...size()-1</code>, returns
175 * the value from the <code>index</code>th key-value mapping that this
176 * SparseLongArray stores.
Flavio Lerda57713022013-09-08 18:04:58 +0100177 *
178 * <p>The values corresponding to indices in ascending order are guaranteed
179 * to be associated with keys in ascending order, e.g.,
180 * <code>valueAt(0)</code> will return the value associated with the
181 * smallest key and <code>valueAt(size()-1)</code> will return the value
182 * associated with the largest key.</p>
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800183 */
184 public long valueAt(int index) {
185 return mValues[index];
186 }
187
188 /**
189 * Returns the index for which {@link #keyAt} would return the
190 * specified key, or a negative number if the specified
191 * key is not mapped.
192 */
193 public int indexOfKey(long key) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700194 return ContainerHelpers.binarySearch(mKeys, mSize, key);
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800195 }
196
197 /**
198 * Returns an index for which {@link #valueAt} would return the
199 * specified key, or a negative number if no keys map to the
200 * specified value.
201 * Beware that this is a linear search, unlike lookups by key,
202 * and that multiple keys can map to the same value and this will
203 * find only one of them.
204 */
205 public int indexOfValue(long value) {
206 for (int i = 0; i < mSize; i++)
207 if (mValues[i] == value)
208 return i;
209
210 return -1;
211 }
212
213 /**
214 * Removes all key-value mappings from this SparseIntArray.
215 */
216 public void clear() {
217 mSize = 0;
218 }
219
220 /**
221 * Puts a key/value pair into the array, optimizing for the case where
222 * the key is greater than all existing keys in the array.
223 */
224 public void append(long key, long value) {
225 if (mSize != 0 && key <= mKeys[mSize - 1]) {
226 put(key, value);
227 return;
228 }
229
Adam Lesinski776abc22014-03-07 11:30:59 -0500230 mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
231 mValues = GrowingArrayUtils.append(mValues, mSize, value);
232 mSize++;
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800233 }
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700234
235 /**
236 * {@inheritDoc}
237 *
238 * <p>This implementation composes a string by iterating over its mappings.
239 */
240 @Override
241 public String toString() {
242 if (size() <= 0) {
243 return "{}";
244 }
245
246 StringBuilder buffer = new StringBuilder(mSize * 28);
247 buffer.append('{');
248 for (int i=0; i<mSize; i++) {
249 if (i > 0) {
250 buffer.append(", ");
251 }
252 long key = keyAt(i);
253 buffer.append(key);
254 buffer.append('=');
255 long value = valueAt(i);
256 buffer.append(value);
257 }
258 buffer.append('}');
259 return buffer.toString();
260 }
Jeff Sharkeydda73b52013-01-18 16:56:49 -0800261}