一:使用Listpublic static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetVal
一:使用List
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
二:使用Set
public static boolean useSet(String[] arr, String targetValue) {
Set set = new HashSet(Arrays.asList(arr));
return set.contains(targetValue);
}
三:使用循环判断
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
四:使用Arrays.binarySearch()
Arrays.binarySearch()
方法只能用于有序数组!!!如果数组无序的话得到的结果就会很奇怪。
查找有序数组中是否包含某个值的用法如下:
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}
--结束END--
本文标题: java判断数组是否包含某个元素
本文链接: https://www.lsjlt.com/news/4108.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0