[英]Android - Check whether a value exist in an Array
I have an array named "bob" which contains values. 我有一个名为“bob”的数组,其中包含值。
String[] bob = { "this", "is", "a", "really", "silly", "list" };
How can I know whether "silly" value exists in the array named bob without iterating through it? 如何知道名为bob的数组中是否存在“愚蠢”值而不迭代它?
You can use List#contains
method. 您可以使用
List#contains
方法。 For that you need to convert your array to a list. 为此,您需要将数组转换为列表。 You can use
Arrays#asList()
method fot that: 你可以使用
Arrays#asList()
方法:
String[] bob = { "this", "is", "a", "really", "silly", "list" };
if (Arrays.asList(bob).contains("silly")) {
// true
}
Convert the Array to List using static Arrays.asList(T)
and check with List.contains(Object)
to check if an object exists in the retuned collection. 使用静态
Arrays.asList(T)
将Array转换为List,并使用List.contains(Object)
检查以检查重新调用的集合中是否存在对象。
String[] bob = { "this", "is", "a", "really", "silly", "list" };
System.out.println(Arrays.asList(bob).contains("silly"));
Traditional way however would be to iterate over the array and check at each element using equals(). 然而,传统的方法是迭代数组并使用equals()检查每个元素。
If you are going to check it a lot you may find it more efficient to use a HashSet
: 如果你要经常检查它,你可能会发现使用
HashSet
更有效:
String[] bob = { "this", "is", "a", "really", "silly", "list" };
Set<String> silly = new HashSet<String>(Arrays.asList(bob));
boolean isSilly = silly.contains("silly");
Here is an easy way to do it: 这是一个简单的方法:
ArrayList list = new ArrayList(Arrays.asList(bob ));
if (list.contains("silly")) {
// my array has silly !
}
The idea is to convert your Array to a ListArray object. 我们的想法是将您的Array转换为ListArray对象。 but it would consume extra memory, so make sure it is worth it before using it.
但它会消耗额外的内存,所以在使用它之前确保它是值得的。
Edit 编辑
If you are after peformance and saving memory you can use binary search algorthem instead: this way you don't have to allocate new objects: 如果你追求性能并节省内存,你可以使用二进制搜索algorthem:这样你就不必分配新的对象了:
Arrays.sort(array)
int value = Arrays.binarySearch(array, "silly");
if (value != -1) {
// my array has silly !
}
above code does not work for me. 上面的代码对我不起作用。 primitive types not allowed i guess.
原始类型不允许我猜。
got to do it manually: 必须手动完成:
char[] charlist = {'a','b','c','d'}
boolean arraycontains = false;
char tester = 'c';
for (int y=0;y<charlist.length;y++){
if (charlist[y] == character) {
arraycontains = true;
break;
}
}
if (arraycontains) {
//true. array contains the tester;
}
else {
//false. array does not contain the tester;
}
:) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.