web123456

Traversal of List collections in Java and comparative analysis of two implementation classes

There are 3 ways to traverse list collections:

package ;

 import ;
 import ;
 import ;

 /**
  * Three types of traversals of list
  * @author Owner
  *
  */
 public class ListTest {

	 public static void main(String[] args) {
		
		 List<String> list = new ArrayList<String>();
		
		 ("a");
		 ("b");
		 ("c");
		 ("c");//Repetitive data can be added
		
		 //Transaction method one
		 for(Iterator<String> iterator = ();();){
			 String value = ();
			
			 (value);
		 }
		
		 //Transaction method two
		 for(String value: list){
			 (value);
		 }
		
		 //Transaction method three
		 for(int i=0;i<();i++){
			 ((i));
		 }
		
	 }
 }

Comparative analysis of three types of traversals:


Method traversal:

Data locking will be performed during execution,  Slightly poor performance,  At the same time, if you want to remove an element during the loop, you can only call the method.  


Method 2 traversal:

The first type of internal call


Method three traversal:

Not locked internally,  The most efficient,  However, when writing multi-threading, you must consider the issue of concurrent operations.


The two main implementation classes of the List interface, ArrayList and LinkedList, can use this method to traverse.


Comparative analysis of ArrayList and LinkedList
a) The ArrayList underlying layer uses array implementation, while the LinkedList underlying layer uses bidirectional linked list implementation.
b) When performing insertion or deletion operations, it is better to use LinkedList.
c) When performing search operations, it is better to use ArrayList.


To put it bluntly, it is sequential storage and chain storage in data structures.