前言:
經常用foreach進行遍歷數據,那么作為JDK1.5新增foreach遍歷的順序怎樣的呢?
代碼測試:
看以下代碼,測試list有序集合foreach循環
1 ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); 2 list.add(2); 3 list.add(3); 4 list.add(4); 5 list.add(5); 6 System.out.println(list); 7 for (Integer i : list) { 8 System.out.print(i); 9 }
結果:
[1, 2, 3, 4, 5]
12345
說明 有續集合foreach遍歷是按照集合儲存的順序遍歷的
那么無序集合是怎樣的,我們以hashSet為例:
HashSet<String> set = new HashSet<String>(); set.add("num1"); set.add("axc"); set.add("gfr"); set.add("wer"); set.add("2354"); System.out.println(set); for (String i : set) { System.out.println(i); } 結果: [gfr, wer, 2354, num1, axc] gfr wer 2354 num1 axc
這里面存儲是無序的,但是foreach遍歷出來的數據還是按照直接輸出集合的順序輸出
總結:
foreach使用方便,在寫代碼中可以經常使用。但也要注意,遍歷過程中刪除數據會報ConcurrentModificationException。