[英]How to check whether element is in the array in java?
How to check whether element is in the array in java? 如何检查元素是否在Java中的数组中?
int[] a = new int[5];
a[0] = 5;
a[1] = 2;
a[2] = 4;
a[3] = 12;
a[4] = 6;
int k = 2;
if (k in a) { // whats's wrong here?
System.out.println("Yes");
}
else {
System.out.println("No");
}
Thanks! 谢谢!
The "foreach" syntax in java is: Java中的“ foreach”语法为:
for (int k : a) { // the ':' is your 'in'
if(k == 2){ // you'll have to check for the value explicitly
System.out.println("Yes");
}
}
You have to do the search yourself. 您必须自己进行搜索。 If the list were sorted, you could use java.util.arrays#binarySearch
to do it for you. 如果列表已排序,则可以使用java.util.arrays#binarySearch
为您完成。
If using java 1.5+ 如果使用Java 1.5+
List<Integer> l1 = new ArrayList<Object>(); //build list
for ( Integer i : l1 ) { // java foreach operator
if ( i == test_value ) {
return true;
}
}
return false;
What's wrong? 怎么了? The compiler should say you that there is no in
keyword. 编译器应该说没有in
关键字。
Normally you would use a loop here for searching. 通常,您将在此处使用循环进行搜索。 If you have many such checks for the same list, sort it and use binary search (using the methods in java.util.Arrays
). 如果对同一列表有很多此类检查,请对其进行排序并使用二进制搜索(使用java.util.Arrays
的方法)。
Instead of taking array you can use ArrayList. 除了使用数组,还可以使用ArrayList。 You can do the following 您可以执行以下操作
ArrayList list = new ArrayList();
list.add(5);
list.add(2);
list.add(4);
list.add(12);
list.add(6);
int k = 2;
if (list.contains(k) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
You will need to iterate over the array comparing each element until you find the one that you are looking for: 您将需要遍历数组,比较每个元素,直到找到所需的元素:
// assuming array a that you defined.
int k = 2;
for(int i = 0; i < a.length; i++)
{
if(k == a[i])
{
System.out.println("Yes");
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.