我有一个String[],其值如下:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

给定字符串s,是否有一种测试VALUES是否包含s的好方法?


当前回答

ObStupidAnswer(但我认为这里有一个教训):

enum Values {
    AB, BC, CD, AE
}

try {
    Values.valueOf(s);
    return true;
} catch (IllegalArgumentException exc) {
    return false;
}

其他回答

使用简单的循环是最有效的方法。

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

由Programcreek提供

您可以使用Apache Commons Lang中的ArrayUtils.contains

公共静态布尔包含(Object[]数组,Object objectToFind)

注意,如果传递的数组为空,则此方法返回false。

还有一些方法可用于所有类型的基元数组。

例子:

String[] fieldsToInclude = { "id", "name", "location" };

if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
    // Do some stuff.
}

Arrays.asList()->然后调用contains()方法将始终有效,但搜索算法要好得多,因为不需要在数组周围创建轻量级列表包装器,这就是Arrays.as list()所做的。

public boolean findString(String[] strings, String desired){
   for (String str : strings){
       if (desired.equals(str)) {
           return true;
       }
   }
   return false; //if we get here… there is no desired String, return false.
}

在下面使用-

    String[] values = {"AB","BC","CD","AE"};
    String s = "A";
    boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));

当我使用基本类型byte和byte[]处理低级Java时,迄今为止我得到的最好的结果是byte-Javahttps://github.com/patrickfav/bytes-java看起来是件很好的工作