Java ArrayList errors caused by iterators when emptying elements

Source: Internet
Author: User

In headfirst Java, example: attacking web games

The code provided in the book to check if the target was hit:

for (DotCom dotcomtotest:dotcomslist) {result = Dotcomtotest.checkyourself (userguess), if (Result.equals ("hit")) { break;} else if (Result.equals ("Kill")) {Dotcomslist.remove (dotcomtotest);

The target list is traversed in the same way as the iterator used, but an error occurs during execution.

Error type: Java.util.abstractlist$itr.next ()

Because the elements in the ArrayList are emptied, resulting in an error in the iterator

A variety of situations can be consulted

http://lggege.iteye.com/blog/249430

Code FIX:

for (int i = 0; i < dotcomslist.size (); i + +) {result = Dotcomslist.get (i). Checkyourself (userguess); if (Result.equals ("H It ")) {break;} else if (Result.equals ("Kill")) {dotcomslist.remove (i); break;}}


Java ArrayList errors caused by iterators when emptying elements

Related Article

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.