Many problems that occur when JAVA collections remove their own set Elements

Source: Internet
Author: User

Many problems that occur when JAVA collections remove their own set Elements
The purpose of a piece of code is to delete the set items that contain the "a" string in the collection:

public class TestForeach {public static void main(String[] args){//ArrayList
 
   lists = new ArrayList
  
   ();Collection
   
     lists = new HashSet
    
     ();lists.add("abvd");lists.add("acvd");lists.add("bvd");lists.add("d");lists.add("a");Iterator
     
       iter = lists.iterator();while(iter.hasNext()){String s = iter.next();if( s.contains("a") ){lists.remove(s);}}System.out.println(lists);}}
     
    
   
  
 


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + 1k3s8rfwzvajuw.vcd4kpha + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140827/20140827085807271.jpg" alt = "\">


When you do not use Iterator to traverse collection elements:

Public class TestForeach {public static void main (String [] args) {ArrayList
 
  
Lists = new ArrayList
  
   
(); Lists. add ("abvd"); lists. add ("acvd"); lists. add ("bvd"); lists. add ("d"); lists. add ("a"); for (int I = 0; I
   
    

Output result:

[Acvd, bvd, d]

The reason why acvd is not deleted is:

In memory, when the "abvd" element of I = 0 is deleted, I ++ and the position I = 0 in lists becomes "acvd", which is the next element of the previous I = 0.


Solution when deleting elements in a set:

① Do not use the collection Object. remove (int I)/remove (Object o); instead, use the remove Method of the Iterator Object.

Cause:

The remove Method in iterator:

② If only one element is deleted, you can use the forin statement to delete the element and use the break to exit the loop.

③ Use CopyOnWriteArrayList to solve such exceptions.

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.