• The variable in the loop condition in the for loop is only valued once! See the last picture specifically
•Foreach statement is newly added to Java 5. Foreach has good performance when iterating through arrays and collections.
•foreach is a simplification of the for statement, but foreach cannot replace the for loop. It can be said that any foreach can be rewritten into a for loop, but the other way around will not work.
•Foreach is not a keyword in java. The loop object of foreach is generally a collection, List, ArrayList, LinkedList, Vector, array, etc.
•Foreach format:
for (element type T, name of element per loop, O: loop object) {
//Operate O
}
1. Common ways to use.
1. Foreach traverses the array.
/** * Description: * Created by ascend on 2016/7/8. */public class Client { public static void main(String[] args) { String[] names = {"beibei", "jingjing"}; for (String name : names) { System.out.println(name); } }}2. Foreach traversal List.
/** * Description: * Created by ascend on 2016/7/8. */public class Client { public static void main(String[] args) { List<String> list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); for(String str : list){ System.out.println(str); } }}2. Limitations.
Although foreach can traverse arrays or collections, it can only be used to traverse and cannot modify arrays or collections during traversal. The for loop can modify source arrays or collections during traversal.
1.Array
/** * Description: * Created by ascend on 2016/7/8. */public class Client { public static void main(String[] args) { String[] names = {"beibei", "jingjing"}; for (String name : names) { name = "huanhuan"; } //foreach System.out.println("foreach:"+Arrays.toString(names)); //for for (int i = 0; i < names.length; i++) { names[i] = "huanhuan"; } System.out.println("for:"+Arrays.toString(names)); }}Output: foreach:[beibei, jingjing]for:[huanhuan, huanhuan]2. Collection
/** * Description: * Created by ascend on 2016/7/8. */public class Client { public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("beibei"); names.add("jingjing"); //foreach for(String name:names){ name = "huanhuan"; } System.out.println(Arrays.toString(names.toArray())); //for for (int i = 0; i < names.size(); i++) { names.set(i,"huanhuan"); } System.out.println(Arrays.toString(names.toArray())); }}Output: [beibei, jingjing][huanhuan, huanhuan]A special place to pay attention to! !
The above article in-depth understanding of for and foreach loops in Java is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.