Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2011 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 
     17 package android.util;
     18 
     19 import com.android.internal.util.ArrayUtils;
     20 
     21 /**
     22  * SparseLongArrays map integers to longs.  Unlike a normal array of longs,
     23  * there can be gaps in the indices.  It is intended to be more memory efficient
     24  * than using a HashMap to map Integers to Longs, both because it avoids
     25  * auto-boxing keys and values and its data structure doesn't rely on an extra entry object
     26  * for each mapping.
     27  *
     28  * <p>Note that this container keeps its mappings in an array data structure,
     29  * using a binary search to find keys.  The implementation is not intended to be appropriate for
     30  * data structures
     31  * that may contain large numbers of items.  It is generally slower than a traditional
     32  * HashMap, since lookups require a binary search and adds and removes require inserting
     33  * and deleting entries in the array.  For containers holding up to hundreds of items,
     34  * the performance difference is not significant, less than 50%.</p>
     35  *
     36  * <p>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>.</p>
     41  */
     42 public class SparseLongArray implements Cloneable {
     43     private int[] mKeys;
     44     private long[] mValues;
     45     private int mSize;
     46 
     47     /**
     48      * Creates a new SparseLongArray containing no mappings.
     49      */
     50     public SparseLongArray() {
     51         this(10);
     52     }
     53 
     54     /**
     55      * Creates a new SparseLongArray containing no mappings that will not
     56      * require any additional memory allocation to store the specified
     57      * number of mappings.  If you supply an initial capacity of 0, the
     58      * sparse array will be initialized with a light-weight representation
     59      * not requiring any additional array allocations.
     60      */
     61     public SparseLongArray(int initialCapacity) {
     62         if (initialCapacity == 0) {
     63             mKeys = ContainerHelpers.EMPTY_INTS;
     64             mValues = ContainerHelpers.EMPTY_LONGS;
     65         } else {
     66             initialCapacity = ArrayUtils.idealLongArraySize(initialCapacity);
     67             mKeys = new int[initialCapacity];
     68             mValues = new long[initialCapacity];
     69         }
     70         mSize = 0;
     71     }
     72 
     73     @Override
     74     public SparseLongArray clone() {
     75         SparseLongArray clone = null;
     76         try {
     77             clone = (SparseLongArray) super.clone();
     78             clone.mKeys = mKeys.clone();
     79             clone.mValues = mValues.clone();
     80         } catch (CloneNotSupportedException cnse) {
     81             /* ignore */
     82         }
     83         return clone;
     84     }
     85 
     86     /**
     87      * Gets the long mapped from the specified key, or <code>0</code>
     88      * if no such mapping has been made.
     89      */
     90     public long get(int key) {
     91         return get(key, 0);
     92     }
     93 
     94     /**
     95      * Gets the long mapped from the specified key, or the specified value
     96      * if no such mapping has been made.
     97      */
     98     public long get(int key, long valueIfKeyNotFound) {
     99         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
    100 
    101         if (i < 0) {
    102             return valueIfKeyNotFound;
    103         } else {
    104             return mValues[i];
    105         }
    106     }
    107 
    108     /**
    109      * Removes the mapping from the specified key, if there was any.
    110      */
    111     public void delete(int key) {
    112         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
    113 
    114         if (i >= 0) {
    115             removeAt(i);
    116         }
    117     }
    118 
    119     /**
    120      * Removes the mapping at the given index.
    121      */
    122     public void removeAt(int index) {
    123         System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
    124         System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
    125         mSize--;
    126     }
    127 
    128     /**
    129      * Adds a mapping from the specified key to the specified value,
    130      * replacing the previous mapping from the specified key if there
    131      * was one.
    132      */
    133     public void put(int key, long value) {
    134         int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
    135 
    136         if (i >= 0) {
    137             mValues[i] = value;
    138         } else {
    139             i = ~i;
    140 
    141             if (mSize >= mKeys.length) {
    142                 growKeyAndValueArrays(mSize + 1);
    143             }
    144 
    145             if (mSize - i != 0) {
    146                 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
    147                 System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
    148             }
    149 
    150             mKeys[i] = key;
    151             mValues[i] = value;
    152             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.
    168      *
    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>
    173      */
    174     public int keyAt(int index) {
    175         return mKeys[index];
    176     }
    177 
    178     /**
    179      * Given an index in the range <code>0...size()-1</code>, returns
    180      * the value from the <code>index</code>th key-value mapping that this
    181      * SparseLongArray stores.
    182      *
    183      * <p>The values corresponding to indices in ascending order are guaranteed
    184      * to be associated with keys in ascending order, e.g.,
    185      * <code>valueAt(0)</code> will return the value associated with the
    186      * smallest key and <code>valueAt(size()-1)</code> will return the value
    187      * associated with the largest key.</p>
    188      */
    189     public long valueAt(int index) {
    190         return mValues[index];
    191     }
    192 
    193     /**
    194      * Returns the index for which {@link #keyAt} would return the
    195      * specified key, or a negative number if the specified
    196      * key is not mapped.
    197      */
    198     public int indexOfKey(int key) {
    199         return ContainerHelpers.binarySearch(mKeys, mSize, key);
    200     }
    201 
    202     /**
    203      * Returns an index for which {@link #valueAt} would return the
    204      * specified key, or a negative number if no keys map to the
    205      * specified value.
    206      * Beware that this is a linear search, unlike lookups by key,
    207      * and that multiple keys can map to the same value and this will
    208      * find only one of them.
    209      */
    210     public int indexOfValue(long value) {
    211         for (int i = 0; i < mSize; i++)
    212             if (mValues[i] == value)
    213                 return i;
    214 
    215         return -1;
    216     }
    217 
    218     /**
    219      * Removes all key-value mappings from this SparseIntArray.
    220      */
    221     public void clear() {
    222         mSize = 0;
    223     }
    224 
    225     /**
    226      * Puts a key/value pair into the array, optimizing for the case where
    227      * the key is greater than all existing keys in the array.
    228      */
    229     public void append(int key, long value) {
    230         if (mSize != 0 && key <= mKeys[mSize - 1]) {
    231             put(key, value);
    232             return;
    233         }
    234 
    235         int pos = mSize;
    236         if (pos >= mKeys.length) {
    237             growKeyAndValueArrays(pos + 1);
    238         }
    239 
    240         mKeys[pos] = key;
    241         mValues[pos] = value;
    242         mSize = pos + 1;
    243     }
    244 
    245     private void growKeyAndValueArrays(int minNeededSize) {
    246         int n = ArrayUtils.idealLongArraySize(minNeededSize);
    247 
    248         int[] nkeys = new int[n];
    249         long[] nvalues = new long[n];
    250 
    251         System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
    252         System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
    253 
    254         mKeys = nkeys;
    255         mValues = nvalues;
    256     }
    257 
    258     /**
    259      * {@inheritDoc}
    260      *
    261      * <p>This implementation composes a string by iterating over its mappings.
    262      */
    263     @Override
    264     public String toString() {
    265         if (size() <= 0) {
    266             return "{}";
    267         }
    268 
    269         StringBuilder buffer = new StringBuilder(mSize * 28);
    270         buffer.append('{');
    271         for (int i=0; i<mSize; i++) {
    272             if (i > 0) {
    273                 buffer.append(", ");
    274             }
    275             int key = keyAt(i);
    276             buffer.append(key);
    277             buffer.append('=');
    278             long value = valueAt(i);
    279             buffer.append(value);
    280         }
    281         buffer.append('}');
    282         return buffer.toString();
    283     }
    284 }
    285