[Java learning notes] <Collection framework> Iterator subinterface ListIterator, java Collection iterator
1 import java. util. arrayList; 2 import java. util. iterator; 3 import java. util. list; 4 5 public class Test3 {6 7 public static void main (String [] args) {8 List list = new ArrayList (); 9 10 list. add ("abc1"); 11 list. add ("abc2"); 12 list. add ("abc3"); 13 list. add ("abc4"); 14 15 Iterator it = list. iterator (); 16 while (it. hasNext () {17 Object obj = it. next (); // java. util. concurrentModificationException18 1 9 if (obj. equals ("abc2") {20 list. add ("abc9"); // during the iterator, do not use the set operation element, which is prone to exceptions. 21 // you can use the subinterface ListIterator of the Iterator interface to complete more operations on elements in the iteration 22} 23 else24 System. out. println ("next:" + obj); 25} 26 System. out. println (list); 27 28} 29 30}
1 import java. util. arrayList; 2 import java. util. list; 3 import java. util. listIterator; 4 5 public class Test3 {6 7 public static void main (String [] args) {8 List list = new ArrayList (); 9 10 list. add ("abc1"); 11 list. add ("abc2"); 12 list. add ("abc3"); 13 list. add ("abc4"); 14 15 System. out. println ("list:" + list); 16 17 ListIterator it = list. listIterator (); // get the object 18 of the list iterator // it can add, delete, modify, and query elements in the iteration process 19 // Note: Only A list set has the iteration function 20 21 System. out. println ("hasNext:" + it. hasPrevious (); // returns the result of an element in front of the current position in the list. True or false22 23 while (it. hasNext () {24 Object obj = it. next (); 25 26 if (obj. equals ("abc2") {27 it. set ("abc9"); // Replace the last element returned by next or previous with the specified Element (optional ). 28} 29} 30 31 System. out. println ("list:" + list); 32 System. out. println (); 33 34 System. out. println ("hasNext:" + it. hasNext (); 35 System. out. println ("hasNext:" + it. hasPrevious (); 36 System. out. println (); 37 38 while (it. hasPrevious () 39 {40 System. out. println ("Previous:" + it. previous (); 41} 42 System. out. println (); 43 44 System. out. println ("list:" + list); 45} 46 47}