For loop enhancement, it is not known before that foreach has such a function, first despise yourself, left to see:
Function:
If list is in foreach: [For (Student stu:list)] This form traverses
At this point, Stu.setname () is equivalent to the name value of the current object in the collection that changes the list.
Equivalent to the original for loop [List.get (i). SetName ();] Statement of the role of nonsense not much to say on the code
Entity class student (just a random one on the line)
PackageCom.core.foreach; Public classStudent {Private intID; PrivateString name; Private intAge ; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } }
Test class Listtest
The result of the two for loop in the method Resetstulist () below is the same
PackageCom.core.foreach;Importjava.util.ArrayList;Importjava.util.List; Public classListtest { Public Static voidMain (string[] args) {List<Student> stulist =setstulist (); List<Student> restulist =resetstulist (stulist); for(inti = 0; I < restulist.size (); i + +) {System.out.println (Restulist.get (i). GetName ()); } } Public StaticList<student>setstulist () {List<Student> stulist =NewArraylist<student>(); for(inti = 0; I < 10; i++) {Student stu=NewStudent (); Stu.setage (i); Stu.setid (i); Stu.setname ("Liu Bei"); Stulist.add (Stu); } returnstulist; } Public StaticList<student> Resetstulist (list<student>stulist) {//for (int i = 0; i < stulist.size (); i++) {//Stulist.get (i). SetName ("Zhang Fei");// } for(Student stu:stulist) {Stu.setid (20); Stu.setage (20); Stu.setname ("Zhang Fei"); } returnstulist; }}
The result is printing 10 "Zhang Fei"
You can also break the point in the For loop, one at a time to see if the list value has been changed.
Java for loop Enhancement (foreach)