Determining the index of an Item on a Form (J2ME)
Question
Given an Item
that has been appended to a Form
, whats the best way to find out what index that item is at on the Form?
Form.append(Item)
will give me the index its initially added at, but if I later insert items before that the index will be out of sync.
Solution
This was the best I could come up with:
private int getItemIndex(Item item, Form form) {
for(int i = 0, size = form.size(); i < size; i++) {
if(form.get(i).equals(item)) {
return i;
}
}
return -1;
}
I haven't actually tested this but it should work, I just don't like having to enumerate every item but then there should never be that many so I guess its ok.
OTHER TIPS
Well, there are just two ways to do this, since the API does not have an indexOf(Item)
method:
- You update the index you get when you add an
Item
. So when you insert anotherItem
before other items, you'll have to update the indices of those items. You could keep some kind of shadow-array for this, but that seems a bit overkill. - You loop through all the items of a form using the
size
andget
methods ofForm
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow