Format:
For (data type variable name: Array or collection) {
SOP (variable);
}
Public Static void function_1 () { //for the object array traversal, can I invoke the method of the object string[] str = {"abc", "Itcast", "CN" }; for (String s:str) { System.out.println (s.length ()); } }
Implementing a For loop, iterating over an array
* Benefits: Less code, convenient for container traversal
* Disadvantages: No index, cannot manipulate elements inside the container
Public Static void function () { int[] arr = {3,1,9,0}; for (int i:arr) { System.out.println (i+1); } System.out.println (arr[0]); }
Enhanced for loop Traversal collection
Public Static void function_2 () { ArrayListnew arraylist<person>(); Array.add (new person ("a", +)); Array.add (new person ("B", ten)); for (person P:array) { System.out.println (p); // System.out.println (p.tostring ()); } }
Java-for iterating through an array