Map.get() Behaviour for objects with an equals() override
So my object is basically a few variables, which I compare in an equals() overridden method.
When I my map contains an object like
{ myvar = 1; othervar = "Hello"; yetanother= 12.4f }
and I map.get(new MyObject(1, "Hello", 12.4f)
with an unrelated but content wise identical object, would it get the entry for the original object?7 Replies
⌛
This post has been reserved for your question.
Hey @Lukas! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.
If your
equals()
and hashCode()
methods are implemented correctly, yes.
Do not override equals()
without also overriding hashCode()
, and use the same member fields to calculate the hash code/equality, otherwise your Map may behave really funky. 🙂
(Also, it would have been really easy to simply try this out.)Thanks, I guess you'Re right about trying, but I would have just noticed it didn't work because I didn't know about also overwriting the hashCode
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
right, but it would have changed your question. 🙂 The requirement to override both methods is mentioned in the documentation of Object, and Map mentions it as well: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html
Map (Java SE 21 & JDK 21)
declaration: module: java.base, package: java.util, interface: Map
Object (Java SE 21 & JDK 21)
declaration: module: java.base, package: java.lang, class: Object
Your IDE might also give you a warning, if you override only one of the methods, but that (of course) depends on your IDE and its configuration.
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.