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
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
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 List
s 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);
}
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;
}