牛魔王的故事
直接上代码:package test.contain.lishaojie;import java.util.Arrays;import java.util.HashSet;import java.util.Set;public class TestContain {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubString[] arr = new String[] { "DD", "CC", "DD", "FF", "KK"};String target ="A";int times = 1000;//次数//转换成list方式long startTime = System.currentTimeMillis();for (int i = 0; i < times; i++) {ByList(arr, target);}long endTime = System.currentTimeMillis();long duration = endTime - startTime;System.out.println("list方式: " + duration / 1000000);//转换成set方式startTime = System.currentTimeMillis();for (int i = 0; i < times; i++) {BySet(arr, target);}endTime = System.currentTimeMillis();duration = endTime - startTime;System.out.println("set方式: " + duration / 1000000);//直接循环方式startTime = System.currentTimeMillis();for (int i = 0; i < times; i++) {ByForLoop(arr, target);}endTime = System.currentTimeMillis();duration = endTime - startTime;System.out.println("循环方式: " + duration / 1000000);//二分法查找startTime = System.currentTimeMillis();for (int i = 0; i < times; i++) {ByArraysBinarySearch(arr, target);}endTime = System.currentTimeMillis();duration = endTime - startTime;System.out.println("二分法查找: " + duration / 1000000);}public static boolean ByList(String[] arr, String targetValue) {return Arrays.asList(arr).contains(targetValue);}public static boolean BySet(String[] arr, String targetValue) {Set set = new HashSet(Arrays.asList(arr));return set.contains(targetValue);}public static boolean ByForLoop(String[] arr, String targetValue) {for(String s: arr){if(s.equals(targetValue))return true;}return false;}public static boolean ByArraysBinarySearch(String[] arr, String targetValue) {int a = Arrays.binarySearch(arr, targetValue);if(a > 0)return true;elsereturn false;}}运行结果如下:list方式: 5set方式: 22循环方式: 2二分法查找: 3经过大量数据测试循环方式效率最高,其次是二分法,最后是list,和set因为因为将数组压入Collection类型中,首先要将数组元素遍历一遍,然后再使用集合类做其他操作。但是list方式明显要比set方式快很多,这是为什么呢?直接看代码:首先@SafeVarargs@SuppressWarnings("varargs")public static List asList(T... a) {return new ArrayList(a);}返回的是ArrayList所以set方式还要进行一次操作将ArrayList转换成set,public HashSet(Collection