package demo8; import java.util.Arrays; public class StringInArray { public static void main(String[] args) { String[] arrays = new String[]{ "中国", "印度", "巴西", "阿根廷", "美国", "加拿大", "俄罗斯", "新西兰", "马来西亚", "菲律宾", "尼泊尔" }; Arrays.sort(arrays); int location = Arrays.binarySearch(arrays, "中国"); if(location < 0){ System.out.println("不存在!"); }else{ System.out.println("存在!"); } location = Arrays.binarySearch(arrays, "印度尼西亚"); if(location < 0){ System.out.println("不存在!"); }else{ System.out.println("存在!"); } } }
Arrays.binarySearch是用二分查找算法进行搜索的,这个算法要求是在以排序的数组上进行的,所以在搜索前需要先对数组进行排序。可以把数组里的内容调整一下顺序,注释掉排序的语句,再看看搜索结果。
没什么结果
不是很明白你想问的问题
sort这个方法是排序,是不会影响到查找的