Nonsense needless to say, directly on the code:
Package stytle;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
/**
* @author Buru
* @date November 29, 2009 15:04:04
* */
public class Forloop {
/**
* Just for Test
*
* @param args
*/
public static void Main (string[] args) {
list<string> list = new arraylist<string> ();
List.add ("Sha");
List.add ("lie");
List.add ("Bao");
/**
* Method One: The most common way to not think
* <p>
* Advantages: More common, easy to understand
* <p>
* Disadvantage: Every time to calculate list.size ()
*/
for (int i = 0; i < list.size (); i++) {
System.out.println (List.get (i));
}
/**
* Method Two: Array length extraction
* <p>
* Advantages: Do not have to calculate every time
* <p>
* Disadvantages: 1, the scope of M is not small enough to violate the minimum scope Principle 2, can not manipulate the size of the list in a for loop, such as to remove or add a new element
*/
int m = List.size ();
for (int i = 0; i < m; i++) {
System.out.println (List.get (i));
}
/**
* Method Three: Array length extraction
* <p>
* Advantages: 1, do not have to calculate every time 2, all variables scoped to follow the principle of the minimum scope
* <p>
* Disadvantages: 1, the scope of M is not small enough to violate the minimum scope Principle 2, can not manipulate the size of the list in a for loop, such as to remove or add a new element
*/
for (int i = 0, n = list.size (); i < n; i++) {
System.out.println (List.get (i));
}
/**
* Method Four: Use the reverse of the wording
* <p>
* Advantages: 1, do not have to calculate every time 2, all variables scoped to follow the principle of the minimum scope
* <p>
* Disadvantages: 1, the results of the order will be anti-2, look not accustomed to, difficult to read
* <p>
* Applicable occasions: not related to the order of the display results: for example, the verification of data before saving
*/
for (int i = List.size ()-1; I >= 0; i--) {
System.out.println (List.get (i));
}
/**
* Method Five: Iterator traversal
* <p>
* Advantages: Simple
* <p>
Disadvantages
*/
for (iterator<string> it = List.iterator (); It.hasnext ();) {
System.out.println (It.next ());
}
/**
* Method Six: jdk1.5 new wording
* <p>
* Advantages: Concise combined with generics use more concise
* <p>
* Disadvantage: jdk1.4 downward incompatible
*/
for (Object o:list) {
System.out.println (o);
}
}
}
6 ways to do a for loop in Java