java数组包含_在Java中,如何检测一个数组中是否包含某一个数据?

展开全部

在Java中,检测一个数组是否包含某一个数据,通常有四种方法:

(1)for循环

(2)转换32313133353236313431303231363533e78988e69d8331333366303861为List,调用Arrays.asList(arr).contains方法

(3)使用Set

(4)使用Arrays.binarySearch()方法

下面为上述四种方法的具体代码实现:

1、使用for循环

public static boolean useLoop(String[] arr, String targetValue) {

for (String s : arr) {

if (s.equals(targetValue))

return true;

}

return false;

}

6af01a9b851490bc4a05b74732f5a361.png

2、转换为List,调用Arrays.asList(arr).contains方法

public static boolean useList(String[] arr, String targetValue) {

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

}

bdf002418c1c937eec9e6ff788941b2f.png

3、使用Set

public static boolean useSet(String[] arr, String targetValue) {

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

return set.contains(targetValue);

}

f1cb29966c11c144ccdf7b824f8efcf9.png

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;

} }

1e8c2a54a1c3662489b37b251af09f99.png

扩展资料:

Java种List列表的contains方法:

该方法是通过遍历集合中的每一个元素并用equals方法比较是否存在指定的元素。

public boolean contains(Object o) {

Iterator it = iterator();

if (o==null) {

while (it.hasNext())

if (it.next()==null)

return true;

} else {

while (it.hasNext())

if (o.equals(it.next()))

return true;

}

return false;

}

0db6bed0a3a20ec9f613108c6607c6a3.png

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值