1.检查数组中是否包含特定值的四种不同方法
1)
使用List:
public static
boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).
contains(targetValue);
}
2)
使用Set:
public static
boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.
contains(targetValue);
}
3)使用一个简单循环:
public static
boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
4)
使用Arrays.binarySearch():
注:下面的代码是错误的,这样写出来仅仅为了理解方便。
binarySearch()只能用于已排好序的数组中。所以,你会发现下面结果很奇怪。
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}
相关文章
- jQuery 判断是否包含在数组中 jQuery.inArray()
- C语言 定义一个整型二维数组,存放一个5×5的矩阵,要求从键盘输入矩阵的值,找出主对角线上其值最大的元素。主对角线如示例中1-4-9-16-25
- js判断数组是否包含某个字符串
- javascript中检测某个字符串在数组中是否存在
- js如何查找数组中是否存在某个值
- 判断某个字符串是否存在于数组中
- Java - 一个”.java”源文件中是否可以包含多个类(不是内部类)?有什么限制?
- 判断python字典或者列表中是否包含某个元素或者key
- js在数组中查找是否存在某一个数值
- JavaScript合并数组对象中key相同的数据(将数组里某个属性相同的对象合并成一个数组)三种方案。