Java traverses the list set and deletes the elements. The two methods are mainly used to traverse the elements that meet certain conditions in the delete set. If you want to delete all elements in the list set, simply use the clear () method in the list interface or directly set its value to null. Method 1:
Public void removelist1 () {list <string> List = new arraylist <string> (); list. add ("B1"); list. add ("B2"); list. add ("B3"); list. add ("B4"); list. add ("B4"); list. add ("B5"); system. out. println ("the collection before deletion is:" + list); system. out. println ("the length of the set before deletion is:" + list. size (); For (INT I = 0, Len = List. size (); I <Len; I ++) {list. remove (I); Len --; // an error is returned if no value is found. I --; // no more elements can be deleted .} System. out. println ("the deleted set is:" + list); system. out. println ("the length of the deleted set is:" + list. size ());}
Method 2:
Public void removelist2 () {list <string> List = new arraylist <string> (); list. add ("B1"); list. add ("B2"); list. add ("B3"); list. add ("B4"); list. add ("B4"); list. add ("B5"); system. out. println ("the collection before deletion is:" + list); system. out. println ("the length of the set before deletion is:" + list. size (); iterator <string> it = List. iterator (); While (it. hasnext ()&&! It. next (). equals ("") {It. remove ();} system. out. println ("the deleted set is:" + list); system. out. println ("the length of the deleted set is:" + list. size ());}
Note: (1) when there is only one element in iterator, its hasnext () method returns true, and its next () method returns the element in it; when there is no element in it, its hasnext () method returns false, and its next () method produces an exception. (2) If you directly traverse the set and call the remove method, you cannot delete all elements. As follows:
Public void removelist3 () {list <string> List = new arraylist <string> (); list. add ("B1"); list. add ("B2"); list. add ("B3"); list. add ("B4"); list. add ("B4"); list. add ("B5"); system. out. println ("the collection before deletion is:" + list); system. out. println ("the length of the set before deletion is:" + list. size (); For (INT I = 0; I <list. size (); I ++) {list. remove (I);} system. out. println ("the deleted collection is:" + list); // You cannot delete all elements. System. Out. println ("the length of the deleted set is:" + list. Size ());}