1 /* 2 * Copyright (C) 2013 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.inputmethod.latin.utils.CollectionUtils; 20 21 import java.util.ArrayList; 22 import java.util.Collections; 23 24 public class SparseArray<E> { 25 private final ArrayList<Integer> mKeys; 26 private final ArrayList<E> mValues; 27 28 public SparseArray() { 29 this(10); 30 } 31 32 public SparseArray(final int initialCapacity) { 33 mKeys = CollectionUtils.newArrayList(initialCapacity); 34 mValues = CollectionUtils.newArrayList(initialCapacity); 35 } 36 37 public int size() { 38 return mKeys.size(); 39 } 40 41 public void clear() { 42 mKeys.clear(); 43 mValues.clear(); 44 } 45 46 public void put(final int key, final E value) { 47 final int index = Collections.binarySearch(mKeys, key); 48 if (index >= 0) { 49 mValues.set(index, value); 50 return; 51 } 52 final int insertIndex = ~index; 53 mKeys.add(insertIndex, key); 54 mValues.add(insertIndex, value); 55 } 56 57 public E get(final int key) { 58 return get(key, null); 59 } 60 61 public E get(final int key, final E valueIfKeyNotFound) { 62 final int index = Collections.binarySearch(mKeys, key); 63 if (index >= 0) { 64 return mValues.get(index); 65 } 66 return valueIfKeyNotFound; 67 } 68 69 public int indexOfKey(final int key) { 70 return mKeys.indexOf(key); 71 } 72 73 public int indexOfValue(final E value) { 74 return mValues.indexOf(value); 75 } 76 77 public int keyAt(final int index) { 78 return mKeys.get(index); 79 } 80 81 public E valueAt(final int index) { 82 return mValues.get(index); 83 } 84 } 85