How to delete objects from a list set

Source: Internet
Author: User

This question seems simple and naive, but it has plagued me for a while, in fact, the root cause of this mistake is our lack of understanding and understanding of the basic knowledge. Some people always think that basic skills are not important, I think that more extensive learning is the most important thing. I think this is easy to make and it is also a fatal incorrect opinion!

If you do not have a strong grasp of the basic knowledge or have a deep understanding, the probability of writing code is 40% incorrect and inefficient. A piece of code does not mean that no compilation error is correct, it is not to say that a simple operation is always right. Excellent code can withstand the challenge of "multithreading, efficiency, and security ).

So I will not emphasize the importance. I believe that after that, the earth will understand what I mean. Let's take a look at this interesting phenomenon.

Let's take a look at the following code:

Import Java. util. arraylist; import Java. util. iterator; import Java. util. list; public class testlist {void Init (list <integer> List) {list. clear (); For (INT I = 0; I <10; I ++) {list. add (I + 1) ;}} void remove (list <integer> List) {for (INT I = 0; I <5; I ++) {list. remove (I) ;}} void removetwo (list <integer> List) {for (int I: List) {if (I <6) {list. remove (I) ;}} void removethree (list <integer> List) {for (iterator <integer> iter = List. iterator (); ITER. hasnext ();) {int I = ITER. next (); if (I <6) {ITER. remove () ;}} public static void main (string [] ARGs) {testlist = new testlist (); List <integer> List = new arraylist <integer> (); // The first method testlist. init (list); testlist. remove (list); system. out. println (list); // The second method try {testlist. init (list); testlist. removetwo (list); system. out. println (list);} catch (exception e) {e. printstacktrace ();} // method testlist. init (list); testlist. removethree (list); system. out. println (list );}}

The running result is as follows:

[2, 4, 6, 8, 10]

Java. util. concurrentmodificationexception

At java. util. effecactlist $ itr. checkforcomodification (effecactlist. Java: 372)

At java. util. abstractlist $ itr. Next (abstractlist. Java: 343)

At com. testlist. removetwo (testlist. Java: 23)

At com. testlist. Main (testlist. Java: 60)

[6, 7, 8, 9, 10]

The above code logic is very simple, that is, to delete the first five objects in the list set, but the results are quite different: the first is the error result, and the second directly reports an exception, only the third one is what we want!

So why? The main reason is the remove () method in the list. Let's analyze:

Method 1:

After the Remove Method is executed for the first time, the first object is not deleted as we simply imagined. The object "1" is deleted, however, after deletion, the index indexes of the nine objects after "2" in the list have also changed, which is one less than the original value, in other words, the index value of the remaining nine objects is from 0 to 8, instead of from 1 to 9. Then, when the Remove Method is executed for the second time, the list. remove (1) deletes the object "3" (the index value of "3" is 1) instead of the expected object "2.

Method 2:

The cause is the same as above. As a result, modcount and expectedmodcount are inconsistent in the next () method of the List, and an exception is thrown.

Therefore, we recommend that you use the third method to delete an object in the list set. This is the simplest and easier to remember. Is there a solution between the first and second methods? Currently, I know the solution of the first method. The second method should be unsolvable (due to the syntax structure ).

Improvement Measures of the first method:

void remove(List<Integer> list) {int num = list.size() - 5;for (int i = 0; i < num; i++) {list.remove(i);i--;num--;}}

I think you have been programming for a long time and will occasionally encounter these simple problems that may cause you a headache. When you encounter these problems, first check whether your logic is faulty, if the logic is correct, check whether there is a problem with the code structure. This is the so-called basic skills. In the future, I will gradually strengthen my basic skills. Let's cheer up.

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.