java 三個循環的優缺點


 1 package cc.knms.appservice.test;
 2 
 3 import java.text.ParseException;
 4 import java.util.ArrayList;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 public class Test {
 9     /**
10      * @autho 方華哥哥
11      * @remark 關於list 性能 ,刪除其中的元素測試
12      *     //附帶說下這三個循環的性能
13      * @date 2016年12月21日 下午1:48:33
14      * @param
15      * @return
16      * @throws ParseException
17      */
18     public static void main(String[] args) throws ParseException {
19         // 循環中 刪除元素測試
20         List<String> list = new ArrayList<String>();
21         list.add("a");
22         list.add("b");
23         list.add("c");
24         list.add("d");
25         list.add("e");
26         
27         
28         for (int i = 0; i < list.size(); i++) {
29             if (list.get(i).equals("b")) {
30                 list.remove(i);
31             }
32             System.out.println(list.get(i));
33             System.out.println(list + "--");
34         }
35         //性能:內部不鎖定,效率最高,但是當寫多線程時要考慮並發操作的問題
36         /* 內部不鎖定也是其缺點,這樣會導致循環當中刪除某個元素可能會出現不必要的問題
37          * 通過結果我們可以看到,在基本的for循環中 我們也能正常的刪除元素,但是這里的指針會向前移動. a b-- c c-- d c-- e
38          * c--
39          */
40         
41         
42     
43         for (String string : list) {
44             if (string.equals("b")) {
45                 list.remove(string);
46             }
47             System.out.println(string);
48         }
49         // 性能:當遍歷集合或數組時,如果需要訪問集合或數組的下標,
50         //     那么最好使用舊式的方式來實現循環或遍歷,而不要使用增強的for循環,因為它丟失了下標信息其實
51 
52         /*
53          * 在增強for循環中刪除元素我們可以看到直接報錯 aException in thread "main" b
54          * java.util.ConcurrentModificationException
55          */
56         
57         
58         Iterator<String> it = list.iterator();
59         while (it.hasNext()) {
60             if (it.next().equals("b")) {
61                 it.remove();
62             }
63             System.out.println(list);
64         }
65         //性能:執行過程中會進行數據鎖定,性能稍差,但是同時,如果你想在循環過程中去掉某個元素,為了避免不必要的問盡量使用it.remove方法;
66         /*
67          * Iterator 也能正常的刪除,在循環中需要刪除數據,然后在獲取某個值的時候建議用Iterator,
68          * 如果用基本的for循環的時候,可能得出的值會錯亂,for循環每刪除一個元素,指針會像前移動,如果通過get去獲取值的時候可能不是自己想要的 
69          * Iterator 則不會
70          *  [a, b, c, d, e] [a, c, d, e] [a, c, d, e] [a,
71          * c, d, e] [a, c, d, e]
72          */
73     }
74 
75 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM