i have a for loop which is adding menuItems to a menu. After adding each menu item, i want to add an actionlistener to it, so when clicked in the menu it will load the corresponding index item from an array. The problem is java will not allow me to call arraylist.get(i) from the anonymous action listener class, as it sais i must be final. i cannot make i final as it increments on each iteration. can anybody help? cheers
Share
Why not extract the element as a
finalreference outside the anonymous class ?Note this is safer for another reason. In your original solution you’re going back to the list and that could potentially change, such that your anonymous class could extract a different object on each callback. In this variant it’s given the
finalreference to the actual instance.