Many issues that occur when the Java collection removes its own collection elements

Source: Internet
Author: User

A piece of code is intended to delete a collection item that contains a string of "a" in the collection:
public class Testforeach {public static void main (string[] args) {//arraylist<string> lists = new Arraylist<strin G> (); collection<string> lists = new hashset<string> () Lists.add ("ABVD"); Lists.add ("Acvd"); Lists.add ("BVD"); Lists.add ("D"); Lists.add ("a");iterator<string> iter = Lists.iterator (); while (Iter.hasnext ()) {String s = Iter.next (); if (S.contains ("a")) {Lists.remove (s);}} SYSTEM.OUT.PRINTLN (lists);}}


Cause Analysis:


When you do not use iterator to traverse a collection element:

public class Testforeach {public static void main (string[] args) {arraylist<string> lists = new arraylist<string& gt; (); Lists.add ("ABVD"); Lists.add ("Acvd"); Lists.add ("BVD"); Lists.add ("D"); Lists.add ("a"); for (int i=0; i< Lists.size (); i++) {String str = lists.get (i), if (Str.contains ("a")) {//lists.remove (i); Lists.remove (str);}} SYSTEM.OUT.PRINTLN (lists);}}

Output Result:

[Acvd, BVD, d]

The reasons why ACVD was not removed are:

In memory, when the element "ABVD" of the i=0 is removed, i++ and the i=0 position in the lists becomes the next element of the ACVD, which is i=0


Solution when deleting elements in the collection:

① do not use collection objects. Remove (int i)/remove (object o), instead use the Remove method of the Iterator object.

Reason:

Remove method in iterator:

② If you delete only one element, you can break out of the loop after you delete the element forin the statement

③ use to solve this kind of anomaly line Shuo complete copyonwritearraylist<e>

Many issues that occur when the Java collection removes its own collection elements

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.