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 missin开发者_JS百科g the correct keywords in the search
Thanks for your time in advance.
int pos = myList.indexOf(myElement);
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)
have a look at ArrayList.indexOf() [specified by List interface]
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)
The following should do the trick:
int index = myList.indexOf(myObject); // Returns -1 if not present.
精彩评论