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