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!

2
  • 4
    why are you calling int[] a list? Its an array, not a list. List means something else in Java Commented Mar 14, 2011 at 18:26
  • 2
    dup stackoverflow.com/questions/1128723/… Commented Mar 14, 2011 at 18:29

6 Answers 6

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");
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Paŭlo - Thanks for the edit. I definitely did not notice that 'if' when I copied over his expression.
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.

Comments

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

Comments

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

Comments

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

Comments

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; 

2 Comments

1) Can't have primitives in a list. 2) It's List, not list. 3) You can't instantiate a List because it's an interface not a class.
You would probably want List<Integer> in this case. Downvote retracted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.