tags:

views:

431

answers:

3

Hello.

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

+3  A: 

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);
}
T.J. Crowder
Thanks.the post was messy because I've accidently confused "remove" and "contains"
Andrey
FFR, the Java Doc specifies when you would receive and IndexOutOfBoundsException, so reversing this logic would give you valid indexes.
Drew
+1  A: 
NawaMan
I don't see why this answer was voted *down*; the proposed expression is correct. It just lacks amplifying explanation.
seh
Thank you, I used your code. I don't know who voted it down, but I think it was voted down because at first it missed part of the code (probably posted accidently forgot to finish it)
Andrey
It was likely partly my fault as I initially forgot the escape '>' and '<' :-p.
NawaMan
A: 

If you have a sparse array (which can contain null values) you might want to check for this as well.

public static boolean isSet(List<?> list, int index) {
   return index >=0 && index < list.size() && list.get(index) != null;
}

Not sure why you would want the index to be Integer type but if you do you should check for null as well. Allowing a null value is the only good reason to have an Integer type.

public static boolean isSet(List<?> list, Integer index) {
   return index != null && index >=0 && index < list.size() && list.get(index) != null;
}
Peter Lawrey