List traversal and deletion elements, list elements
/*** Method for traversing the list * @ param args */public static void main (String [] args) {List <String> list = new ArrayList <String> (); list. add ("111"); list. add ("222"); list. add ("333"); list. add ("222"); list. add ("444"); // 1. for Loop // 1.1 index value I increment // advantage: You can obtain the index value System. out. println ("======= 1. for Loop: 1.1 index value I increments = "); for (int I = 0; I <list. size (); I ++) {System. out. println (list. get (I);} // 1.2 index value I decrease // advantage: Yes To obtain the index value. You can delete the System element. out. println ("======= 1. for Loop: 1.2 index value I decline ====== "); for (int I = list. size ()-1; I> = 0; I --) {System. out. println (list. get (I); if ("444 ". equals (list. get (I) {list. remove (I) ;}// 2. enhance the for loop // disadvantage: you cannot obtain the index value or delete the element System. out. println ("======= 2. enhanced for loop ====== "); for (String str: list) {System. out. println (str);} // 3. iterator (Principle: generate a linked list, store information on a node of the linked list, store the element address of the list in the data part of the node, and traverse the linked list through pointers, To traverse the list .) // Advantage: the element can be deleted. // disadvantage: the index value cannot be obtained. System. out. println ("======= 3. iterator ====== "); Iterator <String> itr = list. iterator (); System. out. println ("the following elements are deleted:"); while (itr. hasNext () {// One-time judgment hasNext (), one-time next () String str = itr. next (); if ("222 ". equals (str) {System. out. println (str); itr. remove () ;}} System. out. println ("print the last remaining elements of the list:"); Iterator <String> itr2 = list. iterator (); for (; itr2.hasNext ();) {System. out. println (itr2.next ());}}
Running result:
======= 1. for Loop: 1.1 index value I increase =======
111
222
333
222
444
======= 1. for Loop: 1.2 index value I decline ======
444
222
333
222
111
======= 2. Enhanced for loop ======
111
222
333
222
======= 3. iterator =====
The following elements are deleted:
222
222
Print the remaining elements of the list:
111
333