1 Importjava.util.ArrayList;2 ImportJava.util.Iterator;3 Importjava.util.List;4 5 Public classTest3 {6 7 Public Static voidMain (string[] args) {8List List =NewArrayList ();9 TenList.add ("ABC1"); OneList.add ("ABC2"); AList.add ("ABC3"); -List.add ("ABC4"); - theIterator it =list.iterator (); - while(It.hasnext ()) { -Object obj = It.next ();//java.util.ConcurrentModificationException - + if(Obj.equals ("ABC2")){ -List.add ("abc9");//In the iterator process, do not use the collection manipulation elements, prone to exceptions. + //You can use the subinterface listiterator of the iterator interface to do more with the elements in the iteration A } at Else -System.out.println ("Next:" +obj); - } - System.out.println (list); - - } in -}
1 Importjava.util.ArrayList;2 Importjava.util.List;3 ImportJava.util.ListIterator;4 5 Public classTest3 {6 7 Public Static voidMain (string[] args) {8List List =NewArrayList ();9 TenList.add ("ABC1"); OneList.add ("ABC2"); AList.add ("ABC3"); -List.add ("ABC4"); - theSystem.out.println ("list:" +list); - -Listiterator it = List.listiterator ();//gets the object of the list iterator - //it can be implemented in the iterative process to complete the deletion and modification of elements + //Note: Only the list collection has this iteration function - +System.out.println ("Hasnext:" +it.hasprevious ());//returns the result of the element before the current position in the list. True or False A at while(It.hasnext ()) { -Object obj =It.next (); - - if(Obj.equals ("ABC2")){ -It.set ("abc9");//replaces the last element returned by next or previous with the specified element (optional action). - } in } - toSystem.out.println ("list:" +list); + System.out.println (); - theSystem.out.println ("Hasnext:" +It.hasnext ()); *System.out.println ("Hasnext:" +it.hasprevious ()); $ System.out.println ();Panax Notoginseng - while(It.hasprevious ()) the { +System.out.println ("Previous:" +it.previous ()); A } the System.out.println (); + -System.out.println ("list:" +list); $ } $ -}
Java Learning Notes < >iterator sub-interface of the collection framework Listiterator