Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7042017
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T02:07:02+00:00 2026-05-28T02:07:02+00:00

I’m creating a Swing application to make a Game with. It creates images in

  • 0

I’m creating a Swing application to make a Game with. It creates images in random locations off the screen and when they leave the screen I would like to remove them. Please take a look at the code snippet:

public void checkTrolls(){ //CAUSES EXCEPTION ERROR WHEN SPRITE EXIT SCREEN
    for(AutomatedSprite a : trolls){
        if(a.getX() < 0 - a.getImage().getWidth())
            trolls.remove(a);
        if(a.getY() < 0 - a.getImage().getWidth())
            trolls.remove(a);
        if(a.getX() > 800)
            trolls.remove(a);
        if(a.getY() > 600)
            trolls.remove(a);
    }
}

@Override
public void run() {
    long beforeTime, timeDiff, sleep;

    beforeTime = System.currentTimeMillis();

    while(true){
        dodger.update(); //update sprite
        if(trolls.size() != 6){
            trolls.add(new AutomatedSprite("images/troll_face.png"));
        }
        for(Sprite troll : trolls){
            troll.update();         //UPDATES MY SPRITES
        }
        checkTrolls();             //CHECKS TROLLS EXITING THE SCREEN
        repaint();

        for(Sprite troll : trolls){
            System.out.println("X: " + troll.getX());
            System.out.println("Y: " + troll.getY());
        }

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = timeDiff - DELAY;

        if(sleep < 0)
            sleep = 5;

        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) { e.printStackTrace(); }

        beforeTime = System.currentTimeMillis();
    }
}

trolls is a Vector of AutomatedSprites, when they leave the screen I get a ConcurrentModificationException, apparently I can’t remove the instances from my vector.

So it seems that I can’t remove anything from the vector while the thread is updating all my sprites, is there a way to pause my thread so I can remove the sprite?

P.S: here is the entire class in case I missed something: Pastebin

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T02:07:02+00:00Added an answer on May 28, 2026 at 2:07 am

    You cannot remove from a collection while iterating over it, this is true for a single threaded environment as well as a multithreaded one. syncrhonized will still cause the issue, Thread.sleep too. Use and Iterator and remove that way.

    public void checkTrolls(){
        for(Iterator<AutomatedSprite> itr = trolls.iterator(); itr.hasNext();){
            AutomatedSpring nextElemnt = itr.next();
            if(youShouldRemoveTheSprite){
                itr.remove();
            }
        }
    }
    

    So here you use the Iterator supplied by your trolls collection. And you are asking the Iterator to safely remove the object from the collection.

    Now if you are executed checkTrolls with multiple threads then you will need to synchronize. You can do that like this

    public synchronized void checkTrolls(){ ...
    

    Edit based on your recent comment/link.

    It isn’t so much you assigning the Iterator.next() to a variable, its that you are invoking iterator.next() many times. Each time you invoke next() you are moving the iterator to the List’s next element. So at the end of one loop iteration you move the iterator to the 6’th element in the list. If you were indexing it instead it would look like:

       for(Iterator<AutomatedSprite> itr = trolls.iterator(); itr.hasNext(); ){
           if(trolls.get(0).getX() < 0 - trolls.get(1).getImage().getWidth() ||      
                          trolls.get(2).getY() < 0 - trolls.get(3).getImage().getWidth() ||
                           trolls.get(4).getX() > 800 ||
                           trolls.get(5).getY() > 600){
                   trolls.remove(trolls.get(5));
           }
    

    Note for this example: indexing at 0,1,2,3,4… is only for demonstration, in practice it would be i = 0; start for loop trolls.get(i++).getX(), trolls.get(i++).getY() and so forth. If your list was 10,000 you would eventually get a NoSuchElementException

    So for example, if you only have 3 trolls, once you get to the 4th itr.next() you’ll get a NoSuchElementException. For that reason you’ll want to store the next() element in a variable and work on that variable so the itr.hasNext(); returns correctly and the itr.remove() too works correctly.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am using Paperclip to handle profile photo uploads in my app. They upload
I would like to count the length of a string with PHP. The string
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I am trying to understand how to use SyndicationItem to display feed which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.