Attempt to override equals() & hashCode() - please point out error(s)!
Nigel Shrin
Ranch Hand
Joined: May 18, 2009
Posts: 119
posted
0
The hashCode() method is based on a Whizlabs example, the rest is not.
Neither equals nor hashCode appear to be overriding the java.lang.object methods, and I do not know why. The signature is the same.
The output is this, which shows that the default methods are still being used?
Constructive comments only please. Thank you.
Nigel
Mike Simmons
Ranch Hand
Joined: Mar 05, 2008
Posts: 2778
2
posted
0
Nigel Shrin wrote:The hashCode() method is based on a Whizlabs example, the rest is not.
Neither equals nor hashCode appear to be overriding the java.lang.object methods, and I do not know why. The signature is the same.
No - hashCode(Object) is different from hashCode(). You're not overriding unless the number and types of the parameters are the same. One has no parameters, while the other has a single Object parameter. Not the same.
And your overriden equals method expects an object of type 'Q64_hashCode_intArray' (not Integer[]).
SCJP, SCWCD, SCJD
Nigel Shrin
Ranch Hand
Joined: May 18, 2009
Posts: 119
posted
0
This is my first attempt at creating my own equals() & hashCode(); it is closer but still not quite right, I realised I need to pass an object and cannot use it to compare arrays within an object.
This is closer, but the last two lines return (equals) TRUE when they should be FALSE, can someone highlight my error please?
I wanted to say this object is equals if the array has five elements and their sum comes to 15, just as an experiment in learning to use equals() and hashCode(). The array is obviously is declared as 5, but it could be a stringBuffer etc. It has no purpose beyond trying to understand the implementation.
Nigel Shrin
Ranch Hand
Joined: May 18, 2009
Posts: 119
posted
0
Ulf Dittmer wrote:You might also want to check out #28 in the JavaBeginnersFaq.
Hi Ulf,
thanks for the links, I bought the Effective Java book after reading them.