The preferred method for traversing a set is for-each.
for(Element e :c){ doSomething(e);}
This is the practice after version 1.5; before Java, the iterator was used.
To find out why it is better than a common for loop or whlie loop, take a look at the code.
Iterator <element> I = C. iterator (); While (I. hasnext () {dosomething (I. next ();} iterator <element> I2 = C. iterator (); While (I. hasnext () {// bug should not call I dosomething (i2.next ());}
The above bug is because we often copy code with the same structure, but variables are used in the scope class and will not be found during compilation, and problems will occur during running.
This bug does not occur for the for loop. the variables of the first for loop cannot be used in the second for loop of the same method. Otherwise, the compilation fails,
This also shows that the for loop is better than the while loop.
For multi-loop iterations, even the old programmer is prone to a mistake.
Example: card is used to represent the card object, Suit color, and rank points.
Collection <suit> suits = arrays. aslist (suit. values); collection <rank> ranks = arrays. aslist (rank. values); List <card> cards = new arraylist <card> (); For (iterator <suit> I = suits. iterator (); I. hasnext () {for (iterator <rank> J = ranks. iterator (); J. hasnext () {cards. add (New card (I. next, J. next); // note }}
Have you found the problem above ?? Many old programmers will suffer from such errors,
cards.add(new Card(i.next,j.next));
Only J pieces of data can be obtained, instead of J pieces of data we want.
The correct method is as follows:
Collection <suit> suits = arrays. aslist (suit. values); collection <rank> ranks = arrays. aslist (rank. values); List <card> cards = new arraylist <card> (); For (iterator <suit> I = suits. iterator (); I. hasnext () {suit = I. next (); // with this added, the I loop should not be placed in J for (iterator <rank> J = ranks. iterator (); J. hasnext () {cards. add (New card (suit, J. next); // note} then there is no need to worry about the double for-each. multiple iterations can be easily solved by using multiple for-each, the preceding bug <PRE name = "code" class = "html"> for (suit S: Suits) {for (rank R: ranks) {cards. add (S, R );}}
In this simple way, we can see that for-each is better than the common for loop and while loop.
Note:
However, for-each cannot be used in the following three cases:
- Filter-If You Need To iterate the set and delete the selected elements, you must use the display iterator to call the Remove Method.
- Conversion -- this is not suitable if you need to traverse the list or array and modify or replace some elements in the list.
- Parallel conversion-control iterator or index variable that needs to be displayed to traverse multiple sets in parallel.