一,先转为List,再使用contains()方法

    String[] strArr = new String[] { "a", "b", "c"};
String str = "c";
List<String> list = Arrays.asList(strArr);
boolean result = list.contains(str);
System.out.println(result); // true

二,使用最基本的for循环

  for循环的方法是效率最高的

    String[] strArr = new String[] { "a", "b", "c" };
String str = "c";
for (int i = 0; i < strArr.length; i++) {
if (strArr[i].equals(str)) {
System.out.println("该元素在数组中: i=" + i); // 该元素在数组中: i=2
}
}

三,使用Apache Commons的ArrayUtils

  Apache Commons类库有很多,几乎大多数的开源框架都依赖于它,Commons中的工具会节省你大部分时间,它包含一些常用的静态方法和Java的扩展。是开发中提高效率的一套框架.

    String[] strArr = new String[] { "a", "b", "c" };
String str = "c";
boolean result = ArrayUtils.contains(strArr, str); // 推荐
System.out.println(result); // true

https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/

04-24 23:50
查看更多