如何測試一個數組是否包含指定的值

簡單且優雅的方法:

  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);
}
相關文章
相關標籤/搜索