Java ForEach loop A delightful shortcut When should

  • Slides: 9
Download presentation
Java For-Each loop A delightful shortcut

Java For-Each loop A delightful shortcut

When should you use for-each? • To access every element in a collection •

When should you use for-each? • To access every element in a collection • NOT if you plan to remove or replace anything!

General form for (Some. Type var : collection){ // the variable var represents //

General form for (Some. Type var : collection){ // the variable var represents // each item in the collection one at a time } Some. Type is any type of Object Collection could be an array, Array. List, set, queue, etc.

Example 1 Given: String[] sa. Words = {“apple”, “banana”, “coconut”, “durian”, “fig”}; “normal” for

Example 1 Given: String[] sa. Words = {“apple”, “banana”, “coconut”, “durian”, “fig”}; “normal” for loop for-each for(int f=0; f<sa. Words. length; f++) for( fruit: sa. Words) System. out. println(sa. Words[f]); System. out. println(fruit);

Example 2 Given: int[] na. Nums = {45, 62, -7, 17, 23}; “normal” for

Example 2 Given: int[] na. Nums = {45, 62, -7, 17, 23}; “normal” for loop for-each for(int n. Temp: na. Nums) for(int n=0; n<na. Nums. length; n++) System. out. println(na. Nums[n]); System. out. println(n. Temp);

Example 3 Given: Array. List<String> a. Bunch = new Array. List<String>(); a. Bunch. add(“dog”);

Example 3 Given: Array. List<String> a. Bunch = new Array. List<String>(); a. Bunch. add(“dog”); a. Bunch. add(“cat”); a. Bunch. add(“bird”); a. Bunch. add(“rat”); for(int n. I=0; n. I<a. Bunch. size(); n. I++) System. out. println(a. Bunch. get(n. I)); for(String s: a. Bunch) System. out. println(a);

With an Array. List you can NOT • Assign values while iterating • Traverse

With an Array. List you can NOT • Assign values while iterating • Traverse 2 structures at once • Access more than 1 element at a time • It always goes from beginning to end.

Iterate the da. Nums array • for( double d: da. Nums){ • System. out.

Iterate the da. Nums array • for( double d: da. Nums){ • System. out. println(d);

Iterate the humanoid. Cryptids Array. List • for(String h: humanoid. Cryptids) • System. out.

Iterate the humanoid. Cryptids Array. List • for(String h: humanoid. Cryptids) • System. out. println(h);