amedley
amedley

Reputation: 121

Java HashMap only returning last element of list

I'm working on a 2D game, and I'm using LWJGL and the Slick-Util library to help. There's nothing too complicated about it and I've programmed much more difficult things before. However, I've encountered a very odd problem with HashMap / Map return values. This is my code regarding the HashMap:

    public Map<String, Texture> textures;

    public void loadTextures()
    {
        textures = new HashMap<String, Texture>();

        textures.put("char_up", main.loadTextureFrom("character/character_up.png"));
        textures.put("char_down", main.loadTextureFrom("character/character_down.png"));
        textures.put("char_right", main.loadTextureFrom("character/character_right.png"));
        textures.put("char_left", main.loadTextureFrom("character/character_left.png"));
    }

However, anytime I use textures.get(frameHere), it ALWAYS returns the LAST item I put for the HashMap, so if my last item was "char_right", it will ALWAYS return the char_right texture, even if I called something like textures.get("char_up"). I tried setting character positions by loading another instance of the texture every time the character changed directions, and it worked perfectly. Meaning, the problem isn't the texture loader or the way I'm getting textures as a value into my HashMap.

This is pretty frustrating and I'm at a huge loss as to what I might be messing up here. Maybe there is something incredibly simple that I'm missing, because I've done this in Java before without a problem, but even with comparison everything looks 100% fine. Any help is GREATLY appreciated. Thanks.

Edit:

Here is my loadTextureFrom() method:

public Texture loadTextureFrom(String path)
{
    try
    {
        return TextureLoader.getTexture("PNG", new FileInputStream(new File("res/textures/" + path)));
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return null;
}

Upvotes: 0

Views: 1478

Answers (2)

Dariusz
Dariusz

Reputation: 22241

Most probably your image loader returns the same object each time it is called, instead of creating a new object. Java Maps only store references to objects, they do not copy them by value.

Make sure to create a new Image object for each new load.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

A common misconception about collections including HashMap, is when adding or putting a key/value/element you are placing a copy of that element. Instead you are placing a copy of the reference to the element.

The problem you describe is only really possible if the main.loadTextureFrom is returning the same image each time. This would work if you used the image before calling this method again, but if you want to save the image, you will need to save a copy of it.

Upvotes: 2

Related Questions