1

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("No");
        }

Thanks!

Bob
  • 10,427
  • 24
  • 63
  • 71

6 Answers6

6

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");
  }
}
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
McStretch
  • 20,495
  • 2
  • 35
  • 40
  • @Paŭlo - Thanks for the edit. I definitely did not notice that 'if' when I copied over his expression. – McStretch Mar 14 '11 at 18:30
1

You have to do the search yourself. If the list were sorted, you could use java.util.arrays#binarySearch to do it for you.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

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; 
Chris K
  • 11,996
  • 7
  • 37
  • 65
0

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).

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
0

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");
}
Umesh K
  • 13,436
  • 25
  • 87
  • 129
0

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;
    }
}
jbranchaud
  • 5,909
  • 9
  • 45
  • 70