Andrey Andrey - 1 month ago 6
Java Question

Java: ArrayList: Determine if entry exists by its index

How can I check if value exist in ArrayList by its index?

Java offers contains(Object) method, but no contains(Integer index) method

Thank you

Answer

Not at all sure what your question is. You talk about seeing if an entry "exists" but then you talk about Java lacking a remove(Object index) method.

Regarding remove: There's the remove(int) method on the List interface implemented by ArrayList. (Java Lists are indexed by int, not by Object.)

Regarding whether an entry "exists" at a given index, if the list's size() method is greater than the index (and the index is non-negative), then there's an entry at that index:

if (index >= 0 && index < list.size()) {
    // An entry exists; hey, let's remove it
    list.remove(index);
}
Comments