一个数组中是否包含某个值

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1.检查数组中是否包含特定值的四种不同方法

1)使用List:

public staticbooleanuseList(String[] arr, String targetValue) {

return Arrays.asList(arr).contains(targetValue);

}

2)使用Set:

public staticbooleanuseSet(String[] arr, String targetValue) {

Set<String> set = new HashSet<String>(Arrays.asList(arr));

return set.contains(targetValue);

}

3)使用一个简单循环:

public staticbooleanuseLoop(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;

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航