標籤:style blog http java color 使用
在我們用ArrayList<E>類調用add或者remove方法後,特別要注意:此時ArrayList的對象的列表的元素個數以及指定索引位置的元素值已經發生了變化。
下面我們舉代碼進行詳細說明。
調用remove方法後發生的的變化
package personal.hushunfeng;/** * @author hushunfeng */import java.util.ArrayList;public class ArrayListTest {public static void main(String[] args) {//產生一個測試ArrayListArrayList<String> arrayList = new ArrayList<String>();arrayList.add("hu");arrayList.add("shun");arrayList.add("feng");//原列表元素個數System.out.println("原列表元素個數:"+arrayList.size());//原清單索引值為1的元素內容System.out.println("原清單索引值為1的元素內容:"+arrayList.get(1));//原清單索引值為2的元素內容System.out.println("原清單索引值為1的元素內容:"+arrayList.get(2));//對原列表調用remove方法arrayList.remove(1);//新列表引值為1的元素內容System.out.println("原清單索引值為1的元素內容:"+arrayList.get(1));//新清單索引值為2的元素內容System.out.println("原清單索引值為1的元素內容:"+arrayList.get(2));}}
運行後的結果:
結果分析:調用remove方法後,arrayList的元素個數為2,原來第3個元素已經自動移成第2個元素。這一點在使用時特別要注意。
根據這一點,我們編寫一段代碼,需要實現的功能:刪除某個字串ArrayList中的每一個長度為奇數的字串。
錯誤碼如下。
package personal.hushunfeng;/** * @author hushunfeng */import java.util.ArrayList;public class ArrayListTest {public static void main(String[] args) {//產生一個測試ArrayListArrayList<String> arrayList = new ArrayList<String>();arrayList.add("hu");arrayList.add("shun");arrayList.add("feng");for(int i=0;i<arrayList.size();i++) {if(arrayList.get(i).length()%2!=0) {arrayList.remove(i);}}//查看結果System.out.println(arrayList);}}
運行後的結果:[shun]
顯然這斷代碼不能實現我們預期的要求。這都是在調用remove方法後,arrayList的size和索引位置元素髮生導致的結果。
錯誤分析如下。
- i=0;size=3,執行remove,刪除hu
- i=1;size=2,執行remove,刪除feng
- i=2;size=1,不執行remove操作
下面我們將上述代碼進行修改。
package personal.hushunfeng;/** * @author hushunfeng */import java.util.ArrayList;public class ArrayListTest {public static void main(String[] args) {//產生一個測試ArrayListArrayList<String> arrayList = new ArrayList<String>();arrayList.add("hu");arrayList.add("shun");arrayList.add("feng");arrayList.add("feng1");arrayList.add("feng12");for(int i=0;i<arrayList.size();i++) {if(arrayList.get(i).length()%2!=0) {arrayList.remove(i);i-- ;}}//查看結果System.out.println(arrayList);}}
運行後的結果:[hu, shun, feng, feng12]
符合要求,if語句裡的i--起到了本質效果,但這樣寫很不規範。
下面參考書上的寫法。
package personal.hushunfeng;/** * @author hushunfeng */import java.util.ArrayList;public class ArrayListTest {public static void main(String[] args) {//產生一個測試ArrayListArrayList<String> arrayList = new ArrayList<String>();arrayList.add("hu");arrayList.add("shun");arrayList.add("feng");arrayList.add("feng1");arrayList.add("feng12");int i = 0;while(i<arrayList.size()) {String element = arrayList.get(i);if(element.length()%2!=0) {//如果能夠刪除成功,則原先後面一個元素 //代替它,繼續判斷這個位置上的元素符不符合要求arrayList.remove(i);}else {//如果刪除不成功,則調到下一個元素i++;}}//查看結果System.out.println(arrayList);}}