Jaya Mayu
Jaya Mayu

Reputation: 17247

Check whether element available in the ArrayList

I have an ArrayList and I've added elements to the ArrayList using mylist.add() method.

I've added around 10 elements and now I want to figure out whether an element is available in the ArrayList, if so what is the index position. How can I acheive this?? the contains method doesn't help.

I searched online but couldn't figure out a tutorial, may be i'm missing the correct keywords in the search

Thanks for your time in advance.

Upvotes: 0

Views: 1310

Answers (5)

JJ.
JJ.

Reputation: 5475

You can use .contains() to test whether an element is in the ArrayList, but it sounds like you want .indexOf() which will return the index of that Object.

See: http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)

Upvotes: 3

Tom Jefferys
Tom Jefferys

Reputation: 13310

The following should do the trick:

int index = myList.indexOf(myObject);  // Returns -1 if not present.

Upvotes: 1

Adithya Surampudi
Adithya Surampudi

Reputation: 4454

Yes, you are looking for indexOf, returns -1 if no element present, see

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)

Upvotes: 1

amit
amit

Reputation: 178451

have a look at ArrayList.indexOf() [specified by List interface]

Upvotes: 1

user647772
user647772

Reputation:

int pos = myList.indexOf(myElement);

Upvotes: 3

Related Questions