Detailed Explanation of Traversal Instance of List Set in Java
- 2021-07-24 10:53:52
- OfStack
1. There are three ways to traverse List
List<String> list = new ArrayList<String>();
list.add("testone");
list.add( " testtwo " );
...
Type 1:
for(Iterator<String> it = list.iterator(); it.hasNext(); ) {
....
}
In this way, data locking will be carried out during the loop execution, and the performance is slightly poor. At the same time, if you want to remove an element during the fun-seeking process, you can only call the it. remove method, but not the list. remove method, otherwise, there will be a concurrent access error.
Type 2:
for(String data : list) {
.....
}
Calling the first kind internally, it is slower than Iterator. This loop has other limitations, so it is not recommended.
Type 3:
for(int i=0; i<list.size(); i++) {
A a = list.get(i);
...
}
Internal locking is the most efficient, but when writing multi-threads, we should consider the problem of concurrent operation.
2. Test examples
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);
}
//list Add to the collection 10 Ten thousand pieces of data
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 Set 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 Set 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);
}
}
3. Test results:
(1), the first time
foreach traversal time: 55
for list. size () Traversal time: 47
iterator traversal time: 51
(2), 2nd time
foreach traversal time: 54
for list. size () Traversal time: 44
iterator traversal time: 50
(3), 3rd time
foreach traversal time: 48
for list. size () Traversal time: 43
iterator traversal time: 44
From the test results, we can clearly see the efficiency!