1 package jalview.ext.android;
4 * Copyright (C) 2006 The Android Open Source Project
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 * SparseIntArrays map integers to integers. Unlike a normal array of integers,
20 * there can be gaps in the indices. It is intended to be more memory efficient
21 * than using a HashMap to map Integers to Integers, both because it avoids
22 * auto-boxing keys and values and its data structure doesn't rely on an extra
23 * entry object for each mapping.
26 * Note that this container keeps its mappings in an array data structure, using
27 * a binary search to find keys. The implementation is not intended to be
28 * appropriate for data structures that may contain large numbers of items. It
29 * is generally slower than a traditional HashMap, since lookups require a
30 * binary search and adds and removes require inserting and deleting entries in
31 * the array. For containers holding up to hundreds of items, the performance
32 * difference is not significant, less than 50%.
36 * It is possible to iterate over the items in this container using
37 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
38 * <code>keyAt(int)</code> with ascending values of the index will return the
39 * keys in ascending order, or the values corresponding to the keys in ascending
40 * order in the case of <code>valueAt(int)<code>.
45 * Imported into Jalview September 2016
47 * Sep 2016 method add(int, int) added for more efficient increment of counts
48 * (a single binary search, rather than one on read and one on write)
50 public class SparseIntArray implements Cloneable
54 private int[] mValues;
59 * Creates a new SparseIntArray containing no mappings.
61 public SparseIntArray()
67 * Creates a new SparseIntArray containing no mappings that will not require
68 * any additional memory allocation to store the specified number of mappings.
69 * If you supply an initial capacity of 0, the sparse array will be
70 * initialized with a light-weight representation not requiring any additional
73 public SparseIntArray(int initialCapacity)
75 if (initialCapacity == 0)
77 mKeys = ContainerHelpers.EMPTY_INTS;
78 mValues = ContainerHelpers.EMPTY_INTS;
82 initialCapacity = idealIntArraySize(initialCapacity);
83 mKeys = new int[initialCapacity];
84 mValues = new int[initialCapacity];
90 public SparseIntArray clone()
92 SparseIntArray clone = null;
95 clone = (SparseIntArray) super.clone();
96 clone.mKeys = mKeys.clone();
97 clone.mValues = mValues.clone();
98 } catch (CloneNotSupportedException cnse)
106 * Gets the int mapped from the specified key, or <code>0</code> if no such
107 * mapping has been made.
109 public int get(int key)
115 * Gets the int mapped from the specified key, or the specified value if no
116 * such mapping has been made.
118 public int get(int key, int valueIfKeyNotFound)
120 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
123 return valueIfKeyNotFound;
132 * Removes the mapping from the specified key, if there was any.
134 public void delete(int key)
136 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
144 * Removes the mapping at the given index.
146 public void removeAt(int index)
148 System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
149 System.arraycopy(mValues, index + 1, mValues, index, mSize
155 * Adds a mapping from the specified key to the specified value, replacing the
156 * previous mapping from the specified key if there was one.
158 public void put(int key, int value)
160 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
168 if (mSize >= mKeys.length)
170 int n = idealIntArraySize(mSize + 1);
171 int[] nkeys = new int[n];
172 int[] nvalues = new int[n];
173 // Log.e("SparseIntArray", "grow " + mKeys.length + " to " + n);
174 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
175 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
181 // Log.e("SparseIntArray", "move " + (mSize - i));
182 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
183 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
192 * Returns the number of key-value mappings that this SparseIntArray currently
201 * Given an index in the range <code>0...size()-1</code>, returns the key from
202 * the <code>index</code>th key-value mapping that this SparseIntArray stores.
205 * The keys corresponding to indices in ascending order are guaranteed to be
206 * in ascending order, e.g., <code>keyAt(0)</code> will return the smallest
207 * key and <code>keyAt(size()-1)</code> will return the largest key.
210 public int keyAt(int index)
216 * Given an index in the range <code>0...size()-1</code>, returns the value
217 * from the <code>index</code>th key-value mapping that this SparseIntArray
221 * The values corresponding to indices in ascending order are guaranteed to be
222 * associated with keys in ascending order, e.g., <code>valueAt(0)</code> will
223 * return the value associated with the smallest key and
224 * <code>valueAt(size()-1)</code> will return the value associated with the
228 public int valueAt(int index)
230 return mValues[index];
234 * Returns the index for which {@link #keyAt} would return the specified key,
235 * or a negative number if the specified key is not mapped.
237 public int indexOfKey(int key)
239 return ContainerHelpers.binarySearch(mKeys, mSize, key);
243 * Returns an index for which {@link #valueAt} would return the specified key,
244 * or a negative number if no keys map to the specified value. Beware that
245 * this is a linear search, unlike lookups by key, and that multiple keys can
246 * map to the same value and this will find only one of them.
248 public int indexOfValue(int value)
250 for (int i = 0; i < mSize; i++)
252 if (mValues[i] == value)
261 * Removes all key-value mappings from this SparseIntArray.
269 * Puts a key/value pair into the array, optimizing for the case where the key
270 * is greater than all existing keys in the array.
272 public void append(int key, int value)
274 if (mSize != 0 && key <= mKeys[mSize - 1])
280 if (pos >= mKeys.length)
282 int n = idealIntArraySize(pos + 1);
283 int[] nkeys = new int[n];
284 int[] nvalues = new int[n];
285 // Log.e("SparseIntArray", "grow " + mKeys.length + " to " + n);
286 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
287 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
292 mValues[pos] = value;
297 * Inlined here by copying from com.android.internal.util.ArrayUtils
302 public static int idealIntArraySize(int need)
304 return idealByteArraySize(need * 4) / 4;
308 * Inlined here by copying from com.android.internal.util.ArrayUtils
313 public static int idealByteArraySize(int need)
315 for (int i = 4; i < 32; i++)
317 if (need <= (1 << i) - 12)
319 return (1 << i) - 12;
330 * This implementation composes a string by iterating over its mappings.
333 public String toString()
339 StringBuilder buffer = new StringBuilder(mSize * 28);
341 for (int i = 0; i < mSize; i++)
350 int value = valueAt(i);
351 buffer.append(value);
354 return buffer.toString();
358 * Method (copied from put) added for Jalview to efficiently increment a key's
359 * value if present, else add it with the given value. This avoids a double
360 * binary search (once to get the value, again to put the updated value).
364 * @return the new value of the count for the key
365 * @throw ArithmeticException if the result would exceed the maximum value of
368 public int add(int key, int toAdd)
370 int newValue = toAdd;
371 int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
374 checkOverflow(mValues[i], toAdd);
376 newValue = mValues[i];
381 if (mSize >= mKeys.length)
383 int n = idealIntArraySize(mSize + 1);
384 int[] nkeys = new int[n];
385 int[] nvalues = new int[n];
386 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
387 System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
393 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
394 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
404 * Throws ArithmeticException if adding addend to value would exceed the range
410 static void checkOverflow(int value, int addend)
413 * test cases being careful to avoid overflow while testing!
417 if (value > 0 && Integer.MAX_VALUE - value < addend)
419 throw new ArithmeticException("Integer overflow adding " + addend
425 if (value < 0 && Integer.MIN_VALUE - value > addend)
427 throw new ArithmeticException("Integer underflow adding " + addend