New Features of JDK5: enhanced for, new features of jdk5
Package cn. itcast. day19.foreach; import java. util. arrayList; import java. util. collection; import java. util. list; import java. util. listIterator;/** New Features of JDK 5: Automatic Disassembly box, generic, variable parameters, enhanced for, static import, and enumeration ** enhanced: is a ** format of for loop: * for (element data type variable: array or Collection set) {**} ** benefits: it simplifies the traversal of arrays and Collection sets ** disadvantages: * 1 the target of enhancement for cannot be null * solution: the target of enhancement for cannot be null, then use * 2 to modify the set during iteration * solution: No! */public class ForEachDemo {public st Atic void main (String [] args) {String [] arr1 = new String [] {"Lin Qingxia", "Feng Qingyang", "", "Sha Monk "}; for (String s: arr1) {System. out. println (s);} System. out. println ("---------"); Collection <String> arr2 = new ArrayList <String> (); arr2.add ("Lin Qingxia"); arr2.add ("Feng Qingyang "); arr2.add (""); arr2.add ("Sha Monk"); for (String s: arr2) {System. out. println (s);} System. out. println ("---------"); // The enhancement for is actually an iterator. // The iterator iterates the set. During the iteration, the set operates the set element. ConcurrentModificationException // for (String s: arr2) {// if ("Lin Qingxia ". equals (s) {// arr2.add ("Sun Wukong"); //} // list iterator iteration set, iterator modify combined with List <String> arr3 = (List <String>) arr2; ListIterator <String> it = arr3.listIterator (); while (it. hasNext () {String s = it. next (); if ("Lin Qingxia ". equals (s) {it. add ("Jay Chou") ;}} System. out. println ("arr3:" + arr3); System. out. println ("---------"); List <String> list = null; // do not perform nul for the target of the enhancement L judgment, and then use if (list! = Null) {// s is taken out of the list. Before getting it, it will definitely determine whether the list has any elements. In this case, if list = null, a null pointer for (String s: list) {System. out. println (s );}}}}