Is there a way to get the index of an item in an array of a given ArrayList?
I know you could use
int test(String item) {
for(int i = 0; i < items.size() && items.contains(item); i++) if(item == items.get(i)) return(i);
return -1;
}
but is it the best way to do it?
Is there something like
int v = items.getIndex(item); //?
Yes, it is indexOf. You can also make a method that gets the position, like this:
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(1);
numbers.add(2);
//first method
int getIndex (int number) {
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) == number) {
return i;
}
}
return 0;
}
//second method
int index = numbers.indexOf(1);