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,123
  • 20
  • 41
Aaron
  • 141
  • 1
  • 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
  • 284,665
  • 62
  • 456
  • 576
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
  • 8,795
  • 8
  • 46
  • 106
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
  • 118,038
  • 37
  • 189
  • 297
0

The ArrayList class provides method contains(Object).

childerico
  • 79
  • 5
0

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

list.contains(7)

harsh
  • 7,322
  • 3
  • 29
  • 31
0

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

Thilo
  • 250,062
  • 96
  • 490
  • 643