赞
踩
Arrays类有一种常用的方法-binarySearch(),可以使用二分搜索法来搜索指定数组,以获得指定对象。该方法返回要搜索元素的索引值。需要注意的是,使用binarySearch()方法前,必须先用Arrays.sort()方法排序,否则结果可能不符合预期。
binarySearch(Object[]a, Object key)
其中参数a表示搜索的数组,参数key表示要搜索的值。以下有两种情况:
example:
public class Test{ public static void main(String[] args){ int[] arr = {4, 3, 1, 9, 5, 8}; ArrayList<Integer> arr1 = new ArrayList<Integer>(); arr1.add(10); arr1.add(4); arr1.add(8); arr1.add(9); arr1.add(-100); Arrays.sort(arr); Collections.sort(arr1); int s1 = Arrays.binarySearch(arr, 6); int s2 = Arrays.binarySearch(arr, 3); int s3 = Arrays.binarySearch(arr, -3); int s4 = Collections.binarySearch(arr1, 0); int s5 = Collections.binarySearch(arr1, 8); System.out.println("s1 value is " + s1); System.out.println("s2 value is " + s2); System.out.println("s3 value is " + s3); System.out.println("s4 value is " + s4); System.out.println("s5 value is " + s5); System.out.println(arr1); } }
output:
s1 value is -5
s2 value is 1
s3 value is -1
s4 value is -2
s5 value is 2
[-100, 4, 8, 9, 10]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。