关于foreach报空指针的代码解释
程序代码:
import java.util.Iterator; import java.util.List; public class Test { public static void main(String[] args) { List<String> list = null; try { for (String string : list) { System.out.println(string); } } catch (Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); } try { for (Iterator iterator = list.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); System.out.println(string); } } catch (Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); } System.out.println("关于foreach报空指针的代码解释!"); } }所以在使用foreach时,有必要对集合做非空校验!!!