java之加強for循環以及幾種刪除集合元素的方式

 1 public class Demo1_Foreach {
 2 
 3     /*
 4      * 加強for循環格式:
 5      *     for(元素數據類型   變量  :  數組或者Collection集合){
 6      *         使用變量便可,該變量就是元素
 7      *     }
 8      * 實質:底層依賴的是迭代器
 9      */
10     public static void main(String[] args) {
11 
12         //demo1();
13         List<String> l = new ArrayList<>();
14         l.add("a");
15         l.add("b");
16         l.add("b");
17         l.add("c");
18         
19         /*
20          * 1. 普通for循環刪除元素
21          *    注意:索引要減減 ( -- )
22          
23         for(int i=0; i < l.size(); i++) {
24             if ("b".equals(l.get(i))) {
25                 //l.remove(i);            //[a, b, c]
26                 l.remove(i--);            //[a, c]
27             }
28         }
29         */
30         
31         /*2.迭代器刪除元素
32          * Iterator<String> it = l.iterator();
33         while (it.hasNext()) {
34             if ("b".equals(it.next())) {
35                 //l.remove("b");   //不能用集合的刪除方法,在遍歷的同時刪除元素,不然會報併發修改異常
36                 it.remove();
37             }
38         }*/
39         
40         /*for(Iterator<String> it2 = l.iterator();it2.hasNext();) {
41             if ("b".equals(it2.next())) {
42                 //l.remove("b");   //不能用集合的刪除方法,在遍歷的同時刪除元素,不然會報併發修改異常
43                 it2.remove();
44             }
45         }*/
46         
47         /*3.加強for循環方式刪除,此方式沒法刪除,由於加強for循環底層依賴的是迭代器,利用集合的刪除方法刪除會報併發修改異常
48          * for (String string : l) {
49             if ("b".equals(string)) {
50                 l.remove("b");
51             }
52         }*/
53         System.out.println(l);
54     }
55 
56     public static void demo1() {
57         int[] arr = {11, 22, 33};
58         for (int i : arr) {
59             System.out.println(i);
60         }
61         
62         ArrayList<String> list = new ArrayList<>();
63         list.add("a");
64         list.add("b");
65         list.add("c");
66         
67         for (String string : list) {
68             System.out.println(string);
69         }
70     }
71 
72 
73 }
74 
75 ///////////////////////////////////////////////////////////////////////////
76 
77 /*
78      * 1. 概述:定義方法時,不知道該定義幾個參數時可使用可變參數
79      * 2.格式:
80      *     修飾符  返回值類型   方法名(數據類型  ... 變量名)
81      *     
82      * 3.注意事項:
83      *     這個可變參數實質就是一個數組
84      *     若是有多個參數,則可變參數必須放到最後一個
85      */
86     public static void main(String[] args) {
87 
88         int[] arr = {11, 22, 33, 44};
89         //print(arr);
90         print(11,33,44);
91     }
92 
93     /*public static void print(int[] arr) {
94         System.out.println(arr[0]);
95     }*/
96     
97     public static void print(int... arr) {
98         System.out.println(arr[0]);
99     }
相關文章
相關標籤/搜索