HashMap doesn't work properly

Discussion in 'Plugin Development' started by Ligachamp, Apr 25, 2016.

Thread Status:
Not open for further replies.
  1. Offline


    Hi guys,

    since I had to change my plugin to use UUID's instead of names to offer new functionality, I've encountered a strange problem (please don't complain about I was using names until now, I had my reasons).

    To the topic:

    I have a HashMap, containing my custom player class "ChunkUpPlayer" as the keys and an integer as the value. However, the map fails to return the proper value using "mymap#containsKey(mykey)". I could add a player as often as I would, the map doesn't recognize it as the same one.

    My ChunkUpPlayer class just stores the UUID and some other plugin-related values. It uses just the UUID to check if it equals another ChunkUpPlayer, which means I DIDN'T FORGET about overwriting the plain "equals" method ;)

    So what I'm missing right now? I've put some verbose outputs everywhere to check if the plugin works the right way, which it seems to... It's 100% surely the HashMap which is driving me nuts...

    For the code look into my github repo, this problem refers to the ChunkData class and the ChunkUpPlayer class, link is here.

  2. Offline


    Your class looks fine for me, you could try to store the UUID directly, just for testing..
  3. Offline


    @Ligachamp A hashmap is primarily based in the object's hashcode, so the first comparison is done with the hashcode and if there are collisions or something with equals

    The problem is that you are overriding equals, but you don't override hashcode so they are considered different objects for the map (unless they get to have the same hashcode, then the map will use equals to know whether they are the same or not)

    So just override hashcode as well, and return the UUID's hashcode
    Ligachamp, mine-care and Lordloss like this.
  4. Offline


    @Konato_K thank you for the explanation! Helps a lot :D
    Just to be curious, but does a Set behave the same way or relies that to other characteristics of an object?
  5. Offline


  6. Offline


    @Konato_K no, I was referring to the Set, not the HashSet. But I guess a look into the javadocs should answer my question :)

    I didn't know that I must override hashcode too, I guess our teacher missed to tell us this particular thing... xD

    EDIT: Now I have another question. In terms of efficiency, has a HashSet or a normal Set the better performance?
    Last edited: Apr 26, 2016
  7. Offline


    @Ligachamp i also read a very complex tutorial about this thematic last days, and not a single word about hashcodes ;)
Thread Status:
Not open for further replies.

Share This Page