1, the For loop and the Foreach Loop function can traverse a list, such as
for (int i = 0; i < list.size; i + +) {
} for
(int i = list.size (); i > 0; I-) {
} for
(Class C:lis T) {
}
2, however, the following case for + + and for--not universal (when the base of the loop changes, for example, the following example, two times per loop inserts an object)
Can do this
for (int i = t.size (); i > 0; I-) {
if (i% 2 = = 0)
t.add (New Test ());
}
But you can't do that.
for (int i = 0; i < t.size (); i + +) {
if (i 2 = = 0)
t.add (New Test ());
}
This is because, in the process of add, the value of T.size () is constantly changing, so this cardinality change can only be used--
3. For the difference between the for and foreach, the relationship of time complexity, foreach is in the constant new object out, such as the following
Package demo_20141031;
Import java.util.ArrayList;
Import java.util.Date;
Import java.util.List;
public class Test {
private String name = "";
Public String GetName () {
// return name; } public
void SetName (String name) {
this.name = name;
}
/**
* @param args
*
/public static void main (string[] args) {
//TODO auto-generated method stub
list<test> t = new arraylist<test> ();
Test temp = new test ();
String a = "n";
String B = "1";
for (int i = 0; i <; i + +) {
temp.setname (a);
T.add (temp);
}
System.out.println (); Long TIME0 = new Date (). GetTime ();
for (int i = 0; i < t.size (); i + +) {
//// }
Long time1 = new Date (). GetTime ();
for (Test temps:t) {
}
long time2 = new Date (). GetTime (); System.out.println (TIME1-TIME0);
System.out.println (time2-time1);
}
}