How to check whether element is in the array in java?
How to check whether element is in the array in 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(开发者_JAVA技巧"No");
}
Thanks!
The "foreach" syntax in java is:
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.
What's wrong? The compiler should say you that there is no in
keyword.
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
).
Instead of taking array you can use 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;
}
}
If using 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;
精彩评论