• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the index of an entry in ArrayList<SelectItem>

Christopher Sharp
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have a JSF application with this code in the xhtml page:

and the corresponding snippets of the Java code are:

Then when a button is clicked for initialization, an action is performed that calls the following method:

and when a button is clicked to submit a selected item, the following code is called:

This works and the menu is shown correctly. When an item is selected and a button clicked, its index is found from prodNum = productValues.indexOf(product);
in the last method above.

That is all well and good, and I've used similar code before. However, I 'm keeping two version of the data, one version in the ArrayList><String> productValues and productLabels, and a copy in SelectItem[] products, thus I'm using three collections instead of one. There must be a better way of doing this.

Accordingly, I replaced these three declarations by:

but left product as a String. The code for the getters and setters were changed to:

The initialization method is now:

Most of this works correctly using only ArrayList SelectItem products without the two ArrayList and the separate SelectItem[], and the values and labels are put directly into products here. The menu works and I can select an item. However, I am unable to find the correct method for finding the index in the submit method,

which has not been changed here. In spite of trying out various ideas, prodNum always returns with -1, which means it cannot find the index of the selected product, where product is a String. Everything else seems to work correctly, and products.get(prodNum).getLabel() works if I manually give prodNum a valid index, but because it's -1 it fails.

I've spent quite a lot of time trying to find out how to fix this problem, but so far without success, and would most appreciate some kind help with this. >
Tim Holloway
Posts: 18408
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm afraid that you explained in such detail that I have no idea what you are actually trying to do.

The easy way to find the index of a selectitem is to simply make its value be the index. Then you can use that to look up whatever additional data items are keyed to that index.

That's assuming, of course, that the index has a useful meaning. Otherwise, of course, you could simply pair the direct value (for example a database key) to the label when building the SelectItem. I've done that as well, so instead of using the index number in cases like that, I'd use the item value as a hash key to one or more tables.

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!