简体   繁体   中英

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("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.

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; 

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM