Java中高效的判断数组中某个元素是否存在详解中高效的判断数组中某个元素是否存在详解
相信大家在操作Java的时候,经常会要检查一个数组(无序)是否包含一个特定的值?这是一个在Java中经常用到
的并且非常有用的操作。同时,这个问题在Stack Overflow中也是一个非常热门的问题。本文将分析几种常见用
法及其时间成本,有需要的朋友们可以参考借鉴。
一、检查数组是否包含某个值的方法一、检查数组是否包含某个值的方法
使用使用List
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
使用使用Set
public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
使用循环判断使用循环判断
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
使用使用Arrays.binarySearch()
Arrays.binarySearch()方法只能用于有序数组!!!如果数组无序的话得到的结果就会很奇怪。
查找有序数组中是否包含某个值的用法如下:
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}
时间复杂度时间复杂度
下面的代码可以大概的得出各种方法的时间成本。基本思想就是从数组中查找某个值,数组的大小分别是5、1k、10k。这种
方法得到的结果可能并不精确,但是是最简单清晰的方式。
public static void main(String[] args) {
String[] arr = new String[] { "CD", "BC", "EF", "DE", "AB"};
//use list
long startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useList(arr, "A");
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("useList: " + duration / 1000000);
//use set
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useSet(arr, "A");
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("useSet: " + duration / 1000000);
//use loop
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useLoop(arr, "A");
}
endTime = System.nanoTime();
评论0