One, the list of the traversal there are three ways
list<string> list = new arraylist<string> ();
List.add ("Testone");
List.add ("Testtwo");
...
The first type:
for (iterator<string> it = List.iterator (); It.hasnext (); ) {
....
}
This way in the loop execution process will be data locking, performance is slightly poor, at the same time, if you want to be able to remove an element in the process, you can only call the It.remove method, you can not use the List.remove method, otherwise there must be a concurrent access error.
The second type:
for (String data:list) {
.....
}
Internal invocation of the first, the bottle, so slower than iterator, this cycle has other limitations, it is not recommended to use it.
The third type:
for (int i=0; I<list.size (); i++) {
A = List.get (i);
...
}
The internal is not locked, the most efficient, but when writing multi-threading to consider the problem of concurrent operations.
Second, the test example
Package com.inspur.Test;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;
/**
* @author WHD
*2015-3-5
*/
@SuppressWarnings ("unused")
public class Maptest {
private static list<string> list= new arraylist<string> ();
public static void Main (String[]args) {
Maptest maptest = new Maptest ();
Maptest.initlist (list);
Maptest.foreach (list);
Maptest.forlist (list);
Maptest.iteratorlist (list);
}
Add 100,000 data to the list collection
Public list initlist (list<string> list) {
int i=0;
int num=6000000;
for (i=0;i<num;i++) {
List.add ("list" +i);
}
return list;
}
List Collection Traversal foreach
public void foreach (List<string> List) {
Long start= system.currenttimemillis ();
for (String data:list) {
String Value=data;
}
Long End=system.currenttimemillis ();
Long Count=end-start;
System.out.println ("foreach Cycle Time" +count);
}
List Collection Traversal for
public void Forlist (list<string> List) {
Long Start=system.currenttimemillis ();
int i=0;
For (I=0;i<list.size (); i++) {
String Value=list.get (i);
}
Long End=system.currenttimemillis ();
Long Count=end-start;
System.out.println ("for list.size () traversal Time" +count);
}
Iterator Traversal loop
public void Iteratorlist (list<string> List) {
Long start= system.currenttimemillis ();
For (iterator<string> it=list.iterator (); It.hasnext ();) {
String Value=it.next ();
}
Long End=system.currenttimemillis ();
Long Count=end-start;
SYSTEM.OUT.PRINTLN ("Iterator Traversal Time" +count);
}
}
Third, the test results:
(1), first time
foreach Traversal time: 55
For List.size () traversal time: 47
Iterator traversal time: 51
(2), second time
foreach Traversal time: 54
For List.size () traversal time: 44
Iterator traversal time: 50
(3), third time
foreach Traversal time: 48
For List.size () traversal time: 43
Iterator traversal time: 44
From the test results we can obviously see the efficiency!
The traversal of the list Java