Java Collections: for-each loop vs index-based loop

One loop works perfectly, the other crashes — both use 'for'! When you start learning Java Collections, this common confusion pops up: ArrayList<Integer> num = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10)); Index-based for loop (works perfectly): for (int i = 0; i < num.size( ); i++) { System.out.println(num.get(i)); // i is the index here } 𝗢𝘂𝘁𝗽𝘂𝘁: 2 4 6 8 10 𝗘𝗻𝗵𝗮𝗻𝗰𝗲𝗱 𝗳𝗼𝗿-𝗲𝗮𝗰𝗵 𝗹𝗼𝗼𝗽 (𝗰𝗼𝗺𝗺𝗼𝗻 𝗺𝗶𝘀𝘁𝗮𝗸𝗲): for (Integer i : num) { System.out.println(num.get(i)); // ❌ WRONG! } In a 𝐟𝐨𝐫-𝐞𝐚𝐜𝐡 𝐥𝐨𝐨𝐩, 𝐢 𝐢𝐬 𝐭𝐡𝐞 𝐚𝐜𝐭𝐮𝐚𝐥 𝐞𝐥𝐞𝐦𝐞𝐧𝐭 𝐯𝐚𝐥𝐮𝐞 (like 2, 4, 6), not the index. So, use i directly—don’t call list.get(i) because it treats i as an index, causing errors. So num.get(i) tries to get element at index 2, then 4, then 6 — but your List only has indices 0 to 4 (since its size is 5). num.get(10) is invalid — this throws IndexOutOfBoundsException because the last valid index is 4. 𝐊𝐞𝐲 𝐩𝐨𝐢𝐧𝐭𝐬 𝐟𝐨𝐫 𝐜𝐥𝐚𝐫𝐢𝐭𝐲: ✅ In index loop: i = index → safe to do num.get(i). ✅ In for-each loop: i = element → just use System.out.println(i) directly. Avoid calling num.get(i) here. 💡 𝐑𝐞𝐦𝐞𝐦𝐛𝐞𝐫: ArrayList grows dynamically when you add elements (add()). But calling get(index) with an out-of-range index will crash your program — it does NOT auto-create elements or indexes. Suresh Bishnoi Sir #ArrayList #Coding #CollectionFrameWork #Java #ForLoop #Code #Tips

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories