Reputation: 11
If I choose never to store my objects in the collection, do I need to override hashcode or can I have the same hashcode for my objects? Is it good or bad for performance?
Upvotes: 1
Views: 199
Reputation: 36
Some others have mentioned just returning a constant value. This might lead to some confusion later on over performance if you forget and put it in a hash based collection. I would consider throwing an UnsupportedOperationException so that if you do want to use it later, you will find out pretty quickly so you can go ahead and do a proper implementation.
Upvotes: 1
Reputation: 108869
Equal objects must have equal hash codes; this is the contract for any class.
If you're feeling too lazy to implement a decent hashCode
method you can still conform to the contract with this implementation:
@Override public int hashCode() {
return 0;
}
It will perform poorly in hash-based collections but will at least be correct.
Upvotes: 4
Reputation: 54242
To address this point:
Is it good or bad for performance?
Either you need it or you don't. If you need it, you don't have a choice. If you don't, it will never be called anyway.
Upvotes: 1
Reputation: 5392
If A.equals(B)
, then A.hashCode() == B.hashCode()
must be true.
If !A.equals(B)
though, A.hashCode() == B.hashCode()
can still be true.
If you don't override hashCode()
when you override equals()
then putting things into some collections will actually lose the objects (they won't retrieve). So either override hashCode()
properly, or just override it to return 1
. This will satisfy the constraints and work correctly, but be terrible for performance if you start putting alot of them in a hash-based collection.
Upvotes: 1
Reputation: 4157
Is it absolutely necessary? No.
Is it a best practice? Yes.
Will it come back to bite you if you don't in 6 months? Maybe.
Upvotes: 5
Reputation: 6006
it will not take much effort for you if you always override these methods, more so modern IDE provide to you this functionality
Upvotes: 2
Reputation: 2489
It is not absolutely necessary, but it is better practice to do so if you ever decide to store and sort the objects later.
Upvotes: 5
Reputation: 15042
Anytime you override hashcode you also need to override equals. Hashcode must return the same value for comparison for which equals returns true, or hashmaps will not work properly.
Yes. Override hashcode if you can improve upon the default implementation.
Upvotes: 0
Reputation: 240870
No you should provide hash code. you never know about tomorrow you may need to use it there
Upvotes: 1