views:

537

answers:

2

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.

A: 

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.

roryf
A: 

Well, there are just two ways to do this, since the API does not have an indexOf(Item) method:

  1. You update the index you get when you add an Item. So when you insert another Item 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.
  2. You loop through all the items of a form using the size and get methods of Form.
Jeroen Heijmans