0

In Python you can do something like

if 7 in list
    return True

Is there anything in java like this? To go "if x in array" without having to do a for loop or several lines of code?

Thanks

opalenzuela
  • 3,139
  • 21
  • 41
Aaron
  • 151
  • 2
  • 2
  • 7
  • try using contains http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value – Lescai Ionel Sep 17 '13 at 11:03
  • 2
    spend 2 seconds on Google before asking... http://stackoverflow.com/questions/3384203/finding-an-element-in-an-array-in-java – Gatekeeper Sep 17 '13 at 11:03
  • Check this link http://stackoverflow.com/questions/3384203/finding-an-element-in-an-array-in-java – Nitish Sep 17 '13 at 11:05

6 Answers6

3

Java arrays don't have such properties, but you can either use a collection (preferable a Set, because the lookup methods are the most efficient) or wrap your array with Arrays.asList()

return Arrays.asList(arr).contains(7)
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
2

You can use

Arrays.asList(yourArray) - convert array to list

and then

.contains(7) - find value at list

Some other solutions: http://javarevisited.blogspot.cz/2012/11/4-ways-to-search-object-in-java-array-example.html

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
0

Convert your array to list using Arrays#asList() and

There is contains() method in List

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

The ArrayList class provides method contains(Object).

childerico
  • 89
  • 6
0

You need to call Collection contains method to check for existense:

list.contains(7)

harsh
  • 7,502
  • 3
  • 31
  • 32
0

If you are already using Commons Lang, there is ArrayUtils#contains.

Thilo
  • 257,207
  • 101
  • 511
  • 656