遍曆List過程中刪除元素的正確做法(轉)

來源:互聯網
上載者:User

標籤:

遍曆List過程中刪除元素的正確做法

 

 

public class ListRemoveTest {

   

3

public static void main(String[] args) {

4

        List<Integer> list = new ArrayList<Integer>();

5

        list.add(1);

6

        list.add(2);

7

        list.add(2);

8

        list.add(3);

9

        list.add(4);

10

 

11

        Iterator<Integer> it = list.iterator();

12

        while (it.hasNext()) {

13

            Integer value = it.next();

14

            if (2 == value) {

15

                it.remove();

16

            }

17

            System.out.println(value);

18

        }

19

        System.out.println("最後結果=" + list.toString());

20

    }

21

}

 

1
2
2
3
4
最後結果=[1, 3, 4]

我們看到兩個2全部被刪除了,最後結果剩下1,3,4完全正確。

但對於iterator的remove()方法,也有需要我們注意的地方:

1、每調用一次iterator.next()方法,只能調用一次remove()方法。

2、調用remove()方法前,必須調用過一次next()方法。

 

原文連結:http://my.oschina.net/jixin/blog/365692

 

轉自:連結

遍曆List過程中刪除元素的正確做法(轉)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.