Which is the most performance efficient implementation for assignCode method from the given options?
Reveal answer
Fill a bubble to check yourself
Which is the most performance efficient implementation for assignCode method from the given options?
code attribute cannot be changed as Item class doesn’t have setter method for it.
for (int i = 0; i < itemList.size(); i++) { if(itemList.get(i) != null) { ((Item)itemList.get(i)).code = 50+i; } }
int i = 0; Item im = null; while (i < itemList.size()) { im = (Item)itemList.get(i); if(im != null) { im.code = 50+i; } i++; }
int i = 0; Item im = null; Iterator itr = itemList.iterator(); while (itr.hasNext()) { im =(Item) itr.next(); im.code = 50+i; i++; }
Option D using Iterator is the most performance efficient because it avoids repeated index calculations and bounds checking that occurs with indexed access in a loop. Iterator is optimized for sequential traversal and minimizes overhead. Option B uses indexed access with itemList.get(i) in each iteration, which recalculates position. Option C is similar to B but with while loop - still uses indexed get(). Iterator approach is generally faster for ArrayList traversal.