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 com.android.inputmethod.compat; 18 19 import java.lang.reflect.Method; 20 import java.util.Arrays; 21 22 public class ArraysCompatUtils { 23 private static final Method METHOD_Arrays_binarySearch = CompatUtils 24 .getMethod(Arrays.class, "binarySearch", int[].class, int.class, int.class, int.class); 25 binarySearch(int[] array, int startIndex, int endIndex, int value)26 public static int binarySearch(int[] array, int startIndex, int endIndex, int value) { 27 if (METHOD_Arrays_binarySearch != null) { 28 final Object index = CompatUtils.invoke(null, 0, METHOD_Arrays_binarySearch, 29 array, startIndex, endIndex, value); 30 return (Integer)index; 31 } else { 32 return compatBinarySearch(array, startIndex, endIndex, value); 33 } 34 } 35 compatBinarySearch(int[] array, int startIndex, int endIndex, int value)36 /* package */ static int compatBinarySearch(int[] array, int startIndex, int endIndex, 37 int value) { 38 if (startIndex > endIndex) throw new IllegalArgumentException(); 39 if (startIndex < 0 || endIndex > array.length) throw new ArrayIndexOutOfBoundsException(); 40 41 final int work[] = new int[endIndex - startIndex]; 42 System.arraycopy(array, startIndex, work, 0, work.length); 43 final int index = Arrays.binarySearch(work, value); 44 if (index >= 0) { 45 return index + startIndex; 46 } else { 47 return ~(~index + startIndex); 48 } 49 } 50 } 51