LongSparseLongArray.java revision 5771302ca13c31cb85f17bc58da8f6f8227c9b85
1/* 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; 20 21import java.util.Arrays; 22 23/** 24 * Map of {@code long} to {@code long}. Unlike a normal array of longs, there 25 * can be gaps in the indices. It is intended to be more memory efficient than using a 26 * {@code HashMap}, both because it avoids 27 * auto-boxing keys and values and its data structure doesn't rely on an extra entry object 28 * for each mapping. 29 * 30 * <p>Note that this container keeps its mappings in an array data structure, 31 * using a binary search to find keys. The implementation is not intended to be appropriate for 32 * data structures 33 * that may contain large numbers of items. It is generally slower than a traditional 34 * HashMap, since lookups require a binary search and adds and removes require inserting 35 * and deleting entries in the array. For containers holding up to hundreds of items, 36 * the performance difference is not significant, less than 50%.</p> 37 * 38 * <p>It is possible to iterate over the items in this container using 39 * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using 40 * <code>keyAt(int)</code> with ascending values of the index will return the 41 * keys in ascending order, or the values corresponding to the keys in ascending 42 * order in the case of <code>valueAt(int)<code>.</p> 43 * 44 * @hide 45 */ 46public class LongSparseLongArray implements Cloneable { 47 private long[] mKeys; 48 private long[] mValues; 49 private int mSize; 50 51 /** 52 * Creates a new SparseLongArray containing no mappings. 53 */ 54 public LongSparseLongArray() { 55 this(10); 56 } 57 58 /** 59 * Creates a new SparseLongArray containing no mappings that will not 60 * require any additional memory allocation to store the specified 61 * number of mappings. If you supply an initial capacity of 0, the 62 * sparse array will be initialized with a light-weight representation 63 * not requiring any additional array allocations. 64 */ 65 public LongSparseLongArray(int initialCapacity) { 66 if (initialCapacity == 0) { 67 mKeys = ContainerHelpers.EMPTY_LONGS; 68 mValues = ContainerHelpers.EMPTY_LONGS; 69 } else { 70 initialCapacity = ArrayUtils.idealLongArraySize(initialCapacity); 71 mKeys = new long[initialCapacity]; 72 mValues = new long[initialCapacity]; 73 } 74 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) { 103 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 104 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) { 116 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 117 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) { 138 int i = ContainerHelpers.binarySearch(mKeys, mSize, key); 139 140 if (i >= 0) { 141 mValues[i] = value; 142 } else { 143 i = ~i; 144 145 if (mSize >= mKeys.length) { 146 growKeyAndValueArrays(mSize + 1); 147 } 148 149 if (mSize - i != 0) { 150 System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); 151 System.arraycopy(mValues, i, mValues, i + 1, mSize - i); 152 } 153 154 mKeys[i] = key; 155 mValues[i] = value; 156 mSize++; 157 } 158 } 159 160 /** 161 * Returns the number of key-value mappings that this SparseIntArray 162 * currently stores. 163 */ 164 public int size() { 165 return mSize; 166 } 167 168 /** 169 * Given an index in the range <code>0...size()-1</code>, returns 170 * the key from the <code>index</code>th key-value mapping that this 171 * SparseLongArray stores. 172 * 173 * <p>The keys corresponding to indices in ascending order are guaranteed to 174 * be in ascending order, e.g., <code>keyAt(0)</code> will return the 175 * smallest key and <code>keyAt(size()-1)</code> will return the largest 176 * key.</p> 177 */ 178 public long keyAt(int index) { 179 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. 186 * 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> 192 */ 193 public long valueAt(int index) { 194 return mValues[index]; 195 } 196 197 /** 198 * Returns the index for which {@link #keyAt} would return the 199 * specified key, or a negative number if the specified 200 * key is not mapped. 201 */ 202 public int indexOfKey(long key) { 203 return ContainerHelpers.binarySearch(mKeys, mSize, key); 204 } 205 206 /** 207 * Returns an index for which {@link #valueAt} would return the 208 * specified key, or a negative number if no keys map to the 209 * specified value. 210 * Beware that this is a linear search, unlike lookups by key, 211 * and that multiple keys can map to the same value and this will 212 * find only one of them. 213 */ 214 public int indexOfValue(long value) { 215 for (int i = 0; i < mSize; i++) 216 if (mValues[i] == value) 217 return i; 218 219 return -1; 220 } 221 222 /** 223 * Removes all key-value mappings from this SparseIntArray. 224 */ 225 public void clear() { 226 mSize = 0; 227 } 228 229 /** 230 * Puts a key/value pair into the array, optimizing for the case where 231 * the key is greater than all existing keys in the array. 232 */ 233 public void append(long key, long value) { 234 if (mSize != 0 && key <= mKeys[mSize - 1]) { 235 put(key, value); 236 return; 237 } 238 239 int pos = mSize; 240 if (pos >= mKeys.length) { 241 growKeyAndValueArrays(pos + 1); 242 } 243 244 mKeys[pos] = key; 245 mValues[pos] = value; 246 mSize = pos + 1; 247 } 248 249 private void growKeyAndValueArrays(int minNeededSize) { 250 int n = ArrayUtils.idealLongArraySize(minNeededSize); 251 252 long[] nkeys = new long[n]; 253 long[] nvalues = new long[n]; 254 255 System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); 256 System.arraycopy(mValues, 0, nvalues, 0, mValues.length); 257 258 mKeys = nkeys; 259 mValues = nvalues; 260 } 261 262 /** 263 * {@inheritDoc} 264 * 265 * <p>This implementation composes a string by iterating over its mappings. 266 */ 267 @Override 268 public String toString() { 269 if (size() <= 0) { 270 return "{}"; 271 } 272 273 StringBuilder buffer = new StringBuilder(mSize * 28); 274 buffer.append('{'); 275 for (int i=0; i<mSize; i++) { 276 if (i > 0) { 277 buffer.append(", "); 278 } 279 long key = keyAt(i); 280 buffer.append(key); 281 buffer.append('='); 282 long value = valueAt(i); 283 buffer.append(value); 284 } 285 buffer.append('}'); 286 return buffer.toString(); 287 } 288} 289