一,先轉為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/
