Re: override equals and hashcode
lowenbrau wrote:
"Lew" <lew@lewscanon.nospam> wrote in message
news:V4adnbv3usKLkybbnZ2dnUVZ_jadnZ2d@comcast.com...
lowenbrau wrote:
Hi,
I have a class Obj. I created three objects o1,o2,03. Objects are equal
if their id is equal. For example, o1 and o3 are equal. I tried adding
these three objects to a HashSet, and when I print the size of the
hashset I get "3" and not "2". Something is not right with the equals or
hashcode method. Can someone shed some light?
code snippet:
boolean equals (Obj o)
{
if (o == null)
return false;
else if (o instanceof Obj)
return (this.id.equals(o.id));
else return false; }
From the JLS
<http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.5>
If a public class has a method or constructor with default access, then
this method or constructor is not accessible to or inherited by a
subclass declared outside this package.
You didn't override equals().
--
Lew
default access?
I don't have a subclass? or any package?
Can you be help some more?
The equals method in Object is declared "public boolean equals(Object obj)"
To override it, you must declare an equals with the same signature. The
only thing you can safely change is the identifier for the parameter:
public boolean equals(Object o)
is fine. Changing anything else will prevent your method from overriding
the Object equals.
Note that when testing an equals implementation it is important to
include tests where the parameter has type Object, even if it references
an instance of your class:
Test someTest = new Test...
Object o1 = someTest;
and use o1 as the equals parameter. That is how it will be used, in
effect, in java.util collections.
[If it were "public boolean equals(SomeClass obj)" you could replace
"SomeClass" with a superclass or super-interface. Object has no
superclasses, so that is not an option for equals.]
Patricia