[mw_shl_code=java,true]package com.sort;
import java.util.ArrayList; import java.util.Iterator; import java.util.List;
/** * Three types of traversal of the list * @author Owner
* */ public class ListTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a"); list.add("b"); list.add("c"); list.add("c"); Duplicate data can be added
Traversal method 1 for(Iterator<String> iterator = list.iterator(); iterator.hasNext(); ){ String value = iterator.next();
System.out.println(value); }
Traversal method 2 for(String value : list){ System.out.println(value); }
Traversal method 3 for(int i=0; i<list.size(); i++){ System.out.println(list.get(i)); }
} } [/mw_shl_code]
Comparative analysis of the three traversals:
Method 1 traversal: During execution, data locking will be carried out, the performance will be slightly worse, and if you want to remove an element during the loop, you can only call the it.remove method.
Method 2 Traversal: Call the first type internally
Method 3: Traversal: It is not locked internally, which is the most efficient, but when writing multithreading, the problem of concurrent operations should be considered
The two main implementations of the List interface, ArrayList and LinkedList, can be traversed in this way Comparative analysis of ArrayList vs LinkedList a) The underlying layer of ArrayList is implemented with arrays, and the underlying layer of LinkedList is implemented with bidirectional linked lists. b) When performing insert or delete operations, it is better to use LinkedList. c) When performing a search operation, it is better to use ArrayList.
To put it bluntly, it is sequential storage and chain storage in the data structure
|