Reputation: 201
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
Upvotes: 0
Views: 10341
Reputation: 1
Maybe you should consider using a HashMap instead of an ArrayList. There is a reason why the method exist(int index) is not implemented for ArrayList (mainly because it takes to much memory to implement an ArrayList for specifics indexes):
int i = 3; int j = 4;
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
hm.put(3, 4);
hm.containsKey(3);
Upvotes: 0
Reputation: 533530
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;
}
Upvotes: 3
Reputation: 25687
How can I check if value exist in ArrayList by its index?
Try this:
int aIndex = ...;
boolean aIsExistByIndex = (aIndex >= 0) && (aIndex < AL.size())
Hope this help :-p
Upvotes: 1
Reputation: 1074465
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);
}
Upvotes: 5