Android List traversal Delete list.remove () obviously deleted a number of results only deleted one

Source: Internet
Author: User

to remove an element during the traversal of the list Correct Practice

public class ListRemoveTest {

3

public static void main(String[] args) {

4

        List<Integer> list = newArrayList<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
Final results =[1, 3, 4]

We saw that two of the 2 were removed and the final result was 1,3,4 completely correct.

But for iterator's remove () method, there are also areas that need our attention:

1, each call Iterator.next () method, can only call the Remove () method once.

2. Before calling the Remove () method, you must call the next () method once.

Android List traversal Delete list.remove () obviously deleted a number of results only deleted one

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.