silvermyth

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            1 隨筆 :: 12 文章 :: 1 評論 :: 0 Trackbacks
              對于Java集合中的List來講,刪除是一個常見的操作,但是也是最容易犯錯誤的地方,尤其對于新手更是如此。筆者在工作中也經常看到一些工作了很長時間的老程序員在這個問題上犯錯誤;在這里,我將通過一個例子,給大家展示如何從List中安全的刪除元素。先看下面的例子:
              假如我有一個List,其中包含了6個元素,我想刪除其中的前面4個,應該如何做;好多程序員不加思索,寫下了下面的代碼:
              
           1private void unSafeDeleteTopByCount(List list) {
           2        try {
           3            for (int i = 0; i < 4; i++{
           4                list.remove(i);
           5            }

           6        }
           catch (Exception e) {
           7            e.printStackTrace();
           8        }
           
              大家可以新建一個List,然后新建一個類在main中調用一下這個方法,看看結果會如何:看到了吧,程序拋出了異常,如下:
              java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
           at java.util.ArrayList.RangeCheck(Unknown Source)
           at java.util.ArrayList.remove(Unknown Source)
           at com.lpx.collection.TestArrayDeletion.unSafeDeleteTopByCount(TestArrayDeletion.java:59)
           at com.lpx.collection.TestArrayDeletion.main(TestArrayDeletion.java:26)
              看到這里,可能大家已經明白了;對了,在刪除的過程中,List的size發生了變化,但是index沒有變化,就會造成index>=size的情況發生,拋出IndexOutOfBoundsException是一定的。這還算好的,至少你知道有異常,但是還有一種更隱蔽的情況,如果你刪除的個數是3個,IndexOutOfBoundsException是不會發生的,但是刪除后的List不是你想要的結果。具體是
          private void unSafeDeleteTopByCount(int count) {
                  
          try {
                      
          for (int i = 0; i < count; i++{
                          list.remove(i);
                      }

                  }
           catch (Exception e) {
                      e.printStackTrace();
                  }
           finally {
                      print();
                  }

              }


          private void print() {
                  
          for (String str : list) {
                      System.out.println(str);
                  }

              }


          List
          <String> list = new ArrayList<String>();
          for(int i=0;i<6;i++){
                 list.add(
          "str"+i);
          }

          unSafeDeleteTopByCount(
          3);
             什么意思呢,大家可以看一下上面的代碼,如果運行的話,打印出的結果是:
              str1
              str3
              str5
             為什么呢,當我們刪除了index為0的元素【str0】后,由于List的size變化,index為0的元素會變為str1,而index為1的元素會變為str2,這時由
          private void safeDeletionTopByCountMethod1(int count) {
                  System.out.println(
          "*********safeDeletionTopByCountMethod1*********");
                  
          for (int i = count - 1; i >= 0; i--{
                      list.remove(i);
                  }

                  print();
              }


              
          private void safeDeletionTopByCountMethod2(int count) {
                  System.out.println(
          "*********safeDeletionTopByCountMethod2*********");
                  
          for (int i = 0; i < count; i++{
                      list.remove(
          0);
                  }

                  print();
              }


              
          private void safeDeletionTopByCountMethod3(int count) {
                  System.out.println(
          "*********safeDeletionTopByCountMethod3*********");
                  List
          <String> localList = new ArrayList<String>();
                  
          for (int i = 0; i < count; i++{
                      localList.add(list.get(i));
                  }

                  list.removeAll(localList);
                  print();
              }


              
          private void safeDeletionTopByCountMethod4(int count) {
                  System.out.println(
          "*********safeDeletionTopByCountMethod4*********");
                  List
          <String> localList = new ArrayList<String>();
                  localList.addAll(list);
                  
          for (int i = 0; i < count; i++{
                      String str 
          = localList.get(i);
                      list.remove(str);
                  }

                  print();
              }
          于index為1,所以str2會被刪除;你可以自己去推算一下結果。
          如何解決這個問題呢,筆者在上面給出了4種方法供大家參考,最后給出了完整的代碼。
          *****************************************************************************

          package com.lpx.collection;

          import java.util.ArrayList;
          import java.util.List;

          public class TestArrayDeletion {

           private List<String> list = null;
           public static String[] array = { "str0", "str1", "str2", "str3", "str4",
             "str5" };

           public TestArrayDeletion() {
            super();
            list = new ArrayList<String>();
           }

           /**
            * @param args
            */
           public static void main(String[] args) {
            TestArrayDeletion arrayDeletion = new TestArrayDeletion();
            arrayDeletion.initList();
            arrayDeletion.unSafeDeleteTopByCount(3);

            arrayDeletion.initList();
            arrayDeletion.unSafeDeleteTopByCount(4);

            arrayDeletion.initList();
            arrayDeletion.safeDeletionTopByCountMethod1(4);

            arrayDeletion.initList();
            arrayDeletion.safeDeletionTopByCountMethod2(4);

            arrayDeletion.initList();
            arrayDeletion.safeDeletionTopByCountMethod3(4);

            arrayDeletion.initList();
            arrayDeletion.safeDeletionTopByCountMethod4(4);

           }

           private void initList() {
            list.clear();
            for (String str : array) {
             list.add(str);
            }
           }

           private void print() {
            for (String str : list) {
             System.out.println(str);
            }
           }

           private void unSafeDeleteTopByCount(int count) {
            System.out.println("*********unSafeDeleteTopByCount*********");
            try {
             for (int i = 0; i < count; i++) {
              list.remove(i);
             }
            } catch (Exception e) {
             e.printStackTrace();
            } finally {
             print();
            }
           }

           private void safeDeletionTopByCountMethod1(int count) {
            System.out.println("*********safeDeletionTopByCountMethod1*********");
            for (int i = count - 1; i >= 0; i--) {
             list.remove(i);
            }
            print();
           }

           private void safeDeletionTopByCountMethod2(int count) {
            System.out.println("*********safeDeletionTopByCountMethod2*********");
            for (int i = 0; i < count; i++) {
             list.remove(0);
            }
            print();
           }

           private void safeDeletionTopByCountMethod3(int count) {
            System.out.println("*********safeDeletionTopByCountMethod3*********");
            List<String> localList = new ArrayList<String>();
            for (int i = 0; i < count; i++) {
             localList.add(list.get(i));
            }
            list.removeAll(localList);
            print();
           }

           private void safeDeletionTopByCountMethod4(int count) {
            System.out.println("*********safeDeletionTopByCountMethod4*********");
            List<String> localList = new ArrayList<String>();
            localList.addAll(list);
            for (int i = 0; i < count; i++) {
             String str = localList.get(i);
             list.remove(str);
            }
            print();
           }
          }

          posted on 2011-06-08 23:28 Gavin Li 閱讀(7897) 評論(0)  編輯  收藏 所屬分類: Java

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 宜宾市| 碌曲县| 临湘市| 平遥县| 香港 | 包头市| 东安县| 馆陶县| 古田县| 惠州市| 桦甸市| 渑池县| 万州区| 玛纳斯县| 建宁县| 确山县| 大足县| 屏山县| 兴宁市| 黑水县| 宁蒗| 邛崃市| 三门峡市| 界首市| 滨海县| 西贡区| 思南县| 泗阳县| 宁夏| 天峻县| 临清市| 玛纳斯县| 乳山市| 汉中市| 嫩江县| 荆门市| 大埔县| 庆城县| 彭阳县| 香港 | 师宗县|