开发者

Check whether element available in the ArrayList

开发者 https://www.devze.com 2023-03-30 10:56 出处:网络
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,

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.
0

精彩评论

暂无评论...
验证码 换一张
取 消