Skip to content

Commit 57d785f

Browse files
author
zhupeiquan
committed
How-can-I-test-if-an-array-contains-a-certain-value.md
1 parent 1d9cfdc commit 57d785f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# 如何测试一个数组是否包含指定的值
2+
3+
指定数组,如:
4+
```
5+
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
6+
```
7+
现在制定一个值 s,有哪些比较好的方式,判断这个数组 VALUES 是否包含值 s?
8+
9+
简单且优雅的方法:
10+
```
11+
Arrays.asList(yourArray).contains(yourValue);
12+
```
13+
14+
问题的本质,其实是一个查找的问题,即查找一个数组是否包含某个值。对于原始类型,若是无序的数组,可以直接写一个 for 循环:
15+
```
16+
public static boolean useLoop(String[] arr, String targetValue) {
17+
for(String s: arr){
18+
if(s.equals(targetValue))
19+
return true;
20+
}
21+
return false;
22+
}
23+
```
24+
若是有序的数组,可以考虑二分查找或者其他查找算法:
25+
```
26+
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
27+
int a = Arrays.binarySearch(arr, targetValue);
28+
if(a >= 0)
29+
return true;
30+
else
31+
return false;
32+
}
33+
```
34+
35+
若数组里包含的是一个个对象,实际上比较就是引用是否相等(String 类型是判断 值是否相等),本质就是比较 hashcode 和 equal 方法,可以考虑使用 List 或者 Set,如下
36+
```
37+
public static boolean useList(String[] arr, String targetValue) {
38+
return Arrays.asList(arr).contains(targetValue);
39+
}
40+
```
41+
42+
```
43+
public static boolean useLoop(String[] arr, String targetValue) {
44+
for(String s: arr){
45+
if(s.equals(targetValue))
46+
return true;
47+
}
48+
return false;
49+
}
50+
```
51+
52+
stackoverflow原址:http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value

0 commit comments

Comments
 (0)