Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an element in an array in Java

Tags:

java

arrays

Does Java have a built-function to allow me to linearly search for an element in an array or do I have to just use a for loop?

like image 748
Casebash Avatar asked Aug 01 '10 23:08

Casebash


People also ask

How do I search for an element in an array Java?

In short, to find elements in an array you should: Create a String array. Use contains(Object[] array, Object objectToFind) method of ArrayUtils to check if the object is in the given array. Use the indexOf(Object[] array, Object objectToFind) method find the index of the given object in the array.

How do you check if an object is in an array Java?

The isArray() method of Class is used to check whether an object is an array or not. The method returns true if the given object is an array. Otherwise, it returns false .


1 Answers

There is a contains method for lists, so you should be able to do:

Arrays.asList(yourArray).contains(yourObject); 

Warning: this might not do what you (or I) expect, see Tom's comment below.

like image 54
Douglas Avatar answered Sep 28 '22 14:09

Douglas