Results 1 to 13 of 13

Thread: HashMap problem

  1. #1
    tcms is offline Member
    Join Date
    May 2013
    Posts
    43
    Rep Power
    0

    Default HashMap problem

    Hello everyone,

    I made this code:
    Java Code:
    public void removerInvasor_LIVE() {
    		int count = 0;
    
    		List<MovingImage> temp = new ArrayList<MovingImage>();
    				for (MovingImage invaders : Map_Inv.keySet()) {
    			if (Map_Inv.get(invaders).ja_morreu()) {
    				Map_Inv.remove(invaders);
    				temp.add(invaders);
    				index.getDisplayer().remove(temp.get(count));
    			}
    		}
    		count++;
    		index.getDisplayer().refresh();
    	}
    and when I run I get "java.util.ConcurrentModificationException".

    So, I made another code with an Iterator, like this:

    Java Code:
    public void removerInvasor_LIVE_teste5(){
    		Iterator<MovingImage> it = Map_Inv.keySet().iterator();
    
    		while (it.hasNext()){
    		  it.next();
    		  if (Map_Inv.get(it).ja_morreu())
    		    it.remove();
    		 }
    	}
    but now I get nullPointerExcepetion, and I think the problem is here "(Map_Inv.get(it).ja_morreu())", because get(it) isn't the right reference..

    Can I solve this?

  2. #2
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: HashMap problem

    java.util.ConcurrentModificationException i think is caused when you try to modify something thats in use, in this case you try to remove something whilst its still being used:

    i order to stop this, create a local variable of the same Type and assign it to the current one being iterated through:

    e.g:

    MovingImage temp = invaders;

    remove(temp);

  3. #3
    tcms is offline Member
    Join Date
    May 2013
    Posts
    43
    Rep Power
    0

    Default Re: HashMap problem

    Like this

    Java Code:
    public void removerInvasor_LIVE() {
            int count = 0;
     
            List<MovingImage> temp = new ArrayList<MovingImage>();
                    for (MovingImage invaders : Map_Inv.keySet()) {
    MovingImage temp = invaders;
                if (Map_Inv.get(invaders).ja_morreu()) {
                    Map_Inv.remove(temp);
                    temp.add(invaders);
                    index.getDisplayer().remove(temp));
                }
            }
            count++;
            index.getDisplayer().refresh();
        }

  4. #4
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: HashMap problem

    try it :) i had that exception and that's how i solved it, it wouldn't allow me to remove an element whilst evaluating it

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default Re: HashMap problem

    Java Code:
    public void removerInvasor_LIVE_teste5(){
    		Iterator<MovingImage> it = Map_Inv.keySet().iterator();
    
    		while (it.hasNext()){
    		  it.next();
    		  if (Map_Inv.get(it).ja_morreu())
    		    it.remove();
    		 }
    	}
    This is th correct way for iterating and removing certain items.
    The problem lies not in using the Iterator, but in these lines:
    Java Code:
    		  it.next();
    		  if (Map_Inv.get(it).ja_morreu())
    next() returns the object you are interested in...that is the object you should be using in the get() call.
    As it is, you are calling get while passing in the Iterator (as you suspect).
    So:
    Java Code:
    MovingImage invaders = it.next();
    then use that as the key rather than the iterator.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,610
    Rep Power
    5

    Default Re: HashMap problem

    Quote Originally Posted by Tolls View Post
    This is th correct way for iterating and removing certain items.
    The problem lies not in using the Iterator, but in these lines:
    In your reply I wasn't certain what you were saying. "is the correct..." or "Isn't the correct..."

    Regards,
    Jim
    Last edited by jim829; 05-16-2013 at 02:18 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default Re: HashMap problem

    It's the correct way, ie using the Iterator.remove() method.
    That's why it's there.
    The error they were getting (the NPE) was simply down to using the iterator itself as the key to the Map, rather than the value returned by next().
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    tcms is offline Member
    Join Date
    May 2013
    Posts
    43
    Rep Power
    0

    Default Re: HashMap problem

    Hi Tools, I made it like this:

    Java Code:
    public void removerInvasor_LIVE_teste5(){
    		Iterator<MovingImage> it = Map_Inv.keySet().iterator();
    
    		while (it.hasNext()){
    			MovingImage invaders = it.next();
    		
    		  if (Map_Inv.get(invaders).ja_morreu())
    		    it.remove();
    		 }
    		 
    	}
    but when the condition "if" is found, I get java.util.ConcurrentModificationException again

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default Re: HashMap problem

    Post the full exception including the stack trace, because the following works:
    Java Code:
    	public static void main(String args[]) {
    		HashMap<String, String> map = new HashMap<>();
    		map.put("test", "4test");
    		map.put("test1", "1test");
    		map.put("test2", "test");
    		map.put("test3", "3test");
    		Iterator<String> it = map.keySet().iterator();
    		while (it.hasNext()) {
    			String invaders = it.next();
    			if (map.get(invaders).equals("test")) {
    				it.remove();
    			}
    		}
    		for (Entry<String, String> entry : map.entrySet()) {
    			System.out.println(entry.getKey() + " " + entry.getValue());
    		}
    	}
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    tcms is offline Member
    Join Date
    May 2013
    Posts
    43
    Rep Power
    0

    Default Re: HashMap problem

    My MAP is this:

    Java Code:
    	private Map<MovingImage, Invaders> Map_Inv = new HashMap<MovingImage, Invaders>();
    the Method ja_morreu() (from Invaders) is this:

    Java Code:
            public int getLife() {
    		return life;
    	}
    
    		public boolean ja_morreu() {
    		return (getLife() <= 0);
    	}
    and when I run i get this:

    Java Code:
    Exception in thread "main" java.util.ConcurrentModificationException
    	at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
    	at java.util.HashMap$KeyIterator.next(Unknown Source)
    	at pt.iul.poo.games.Mapa.towerShots(Mapa.java:129)
    	at pt.iul.poo.games.Mapa.game_start(Mapa.java:179)
    	at pt.iul.poo.games.teste_main.main(teste_main.java:27)
    )

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default Re: HashMap problem

    That stack trace does not match the code in post #8.
    The method in that post is called removerInvasor_LIVE_teste5 which does not appear in there.
    You need to show us the towerShots() method, which is where (in your code) this is coming from.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  12. #12
    tcms is offline Member
    Join Date
    May 2013
    Posts
    43
    Rep Power
    0

    Default Re: HashMap problem

    Quote Originally Posted by Tolls View Post
    That stack trace does not match the code in post #8.
    The method in that post is called removerInvasor_LIVE_teste5 which does not appear in there.
    You need to show us the towerShots() method, which is where (in your code) this is coming from.
    here is:
    Java Code:
    if (shot != null)
    			index.getDisplayer().remove(shot);
    
    		for (SimpleImage tower : InsertedTowersImages) {
    		
    				for (MovingImage x : Map_Inv.keySet()) {
    					removerInvasor_LIVE_teste5();
    					if (Math.abs(tower.getPosition().distance(x.getPosition())) < RANGE) {
    						Map_Inv.get(x).ReduzirVida();
    
    						SimpleShape s = new SimpleShape(new Line2D.Double(tower
    								.getPosition().getX()
    								+ tower.getDimension().width / 2, tower
    								.getPosition().getY()
    								+ tower.getDimension().height / 2, x
    								.getPosition().getX()
    								+ x.getDimension().width
    								/ 2, x.getPosition().getY()
    								+ x.getDimension().height / 2), Color.RED, 50);
    						shot = s;
    						index.getDisplayer().add(s);
    					}
    				}
    			}
    		}
    I run the code and sometimes it works well, why?

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default Re: HashMap problem

    And can you show which line in that lot the exception is being thrown from?

    You need to show us the actual code, and point out where the problem is occurring in that code.
    I'm guessing it's here:
    Java Code:
    for (MovingImage x : Map_Inv.keySet())
    and since you call that other method while looping over this keySet, and both create an iterator on the same keySet, and one of them deletes from the keySet, then this iterator will throw an error.

    You cannot change the underlying data being used by an iterator except through that iterator. Doing so will result in a ConcurrentModException.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. HashMap problem
    By Java Junior in forum Advanced Java
    Replies: 6
    Last Post: 03-16-2012, 06:03 PM
  2. HashMap problem
    By vince8864 in forum New To Java
    Replies: 1
    Last Post: 02-13-2012, 11:51 AM
  3. hashmap or search problem
    By flushdabuffer in forum Android
    Replies: 0
    Last Post: 04-09-2011, 01:55 PM
  4. hashmap problem
    By minotaurus in forum Advanced Java
    Replies: 5
    Last Post: 03-16-2011, 11:24 AM
  5. Problem with HashMap
    By maz09 in forum New To Java
    Replies: 2
    Last Post: 04-14-2010, 09:40 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •