如何测试一个数组是否包含指定的值

简单且优雅的方法:

  1. Arrays.asList(...).contains(...)java

  2. 使用 Apache Commons Lang包中的ArrayUtils.contains算法

String[] fieldsToInclude = { "id", "name", "location" };
if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) { 
       // Do some stuff.
   }

本身写逻辑

问题的本质,实际上是一个查找的问题,即查找一个数组是否包含某个值。对于原始类型,如果无序的数组,能够直接写一个 for 循环:数组

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

如果有序的数组,能够考虑二分查找或者其余查找算法:oop

public static boolean useArraysBinarySearch(String[] arr, String targetValue) { 
    int a =  Arrays.binarySearch(arr, targetValue);
    if(a >= 0)
        return true;
    else
        return false;
}

若数组里包含的是一个个对象,实际上比较就是引用是否相等(String 类型是判断值是否相等),本质就是比较 hashcode 和 equal 方法,能够考虑使用 List 或者 Set,以下spa

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