# 四种不同方式来检查数组是否包含某个值

## 1、使用List：

    public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}

## 2、使用Set：

    public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}

## 3、使用简单的循环语句：

    public static boolean useLoop(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
}

## 4、使用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：

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();
duration = endTime - startTime;
System.out.println("useLoop: " + duration / 1000000);
// use Arrays.binarySearch()
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useArraysBinarySearch(arr, "A");
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("useArrayBinary: " + duration / 1000000);
}

## 数组大小为1000：

        String[] arr = new String[1000];
Random s = new Random();
for (int i = 0; i < 1000; i++) {
arr[i] = String.valueOf(s.nextInt());
}

## 数组大小为10000：

        String[] arr = new String[10000];
Random s = new Random();
for (int i = 0; i < 10000; i++) {
arr[i] = String.valueOf(s.nextInt());
}

# 结论

posted @ 2016-05-12 11:08  风一样的码农  阅读(9088)  评论(0编辑  收藏  举报