您的位置:首页 > 其它

判断数组中是否存在某一元素

2017-04-07 15:12 267 查看
## 方法

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
// 检查数组是否包含某个值的方法
public class TestArray {
// 使用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<String> set = new HashSet<String>(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;
}
// 查找有序数组中是否包含某个值的用法
public static boolean useArraysBinarySearch(String[] arr, String targetValue){
int a=Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}
}
/*
* 显然,使用一个简单的循环方法比使用任何集合都更加高效。许多开发人员为了方便,都使用第一种方法,但是他的效率也相对较低。因为将数组压入Collection类型中,首先要将数组元素遍历一遍,然后再使用集合类做其他操作。
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: