1 Public classDemo1_foreach {2 3 /*4 * Enhanced for loop format:5 * for (element data type variable: Array or Collection collection) {6 * Use a variable, which is the element7 * }8 * Essence: The underlying dependency is the iterator9 */Ten Public Static voidMain (string[] args) { One A //demo1 (); -list<string> L =NewArraylist<>(); -L.add ("a"); theL.add ("B"); -L.add ("B"); -L.add ("C"); - + /* - * 1. Normal for loop delete element + * Note: Index to reduce (--) A at for (int i=0; i < l.size (); i++) { - if ("B". Equals (L.get (i))) { - //l.remove (i); [A, B, c] - L.remove (i--); [A, C] - } - } in */ - to /*2. iterators Delete elements + * iterator<string> it = L.iterator (); - While (It.hasnext ()) { the if ("B". Equals (It.next ())) { * //l.remove ("B"); You cannot use the Delete method of a collection to delete an element while traversing, otherwise the concurrency modification exception is reported . $ It.remove ();Panax Notoginseng } - }*/ the + /*For (iterator<string> it2 = L.iterator (); It2.hasnext ();) { A if ("B". Equals (It2.next ())) { the //l.remove ("B"); You cannot use the Delete method of a collection to delete an element while traversing, otherwise the concurrency modification exception is reported . + It2.remove (); - } $ }*/ $ - /*3. Enhanced for loop Delete, this mode cannot be deleted, because the enhanced for loop underlying dependency is an iterator that uses the Delete method of the collection to delete the reported concurrency modification exception - * for (String string:l) { the if ("B". Equals (String)) { - L.remove ("B");Wuyi } the }*/ - System.out.println (l); Wu } - About Public Static voiddemo1 () { $ int[] arr = {11, 22, 33}; - for(intI:arr) { - System.out.println (i); - } A +arraylist<string> list =NewArraylist<>(); theList.add ("a"); -List.add ("B"); $List.add ("C"); the the for(String string:list) { the System.out.println (string); the } - } in the the } About the /////////////////////////////////////////////////////////////////////////// the the /* + * 1. Overview: When defining a method, you do not know that you can use a variable parameter when you define several parameters - * 2. Format: the * Modifier return value type method name (data type ... Variable name)Bayi * the * 3. Precautions: the * This mutable parameter is essentially an array - * If there are multiple parameters, the variable parameter must be placed in the last - */ the Public Static voidMain (string[] args) { the the int[] arr = {11, 22, 33, 44}; the //print (arr); -Print (11,33,44); the } the the /*Public static void print (int[] arr) {94 System.out.println (arr[0]); the }*/ the the Public Static voidPrintint... arr) {98System.out.println (arr[0]); About}
Java enhancements for loops and several ways to delete collection elements