Stuart Ballard writes:
> Andrew Haley <aph <at> redhat.com> writes:
> > No, that's not what I mean by illegal. It's illegal in the sense that
> > the specification places requirements on the implementors of
> > subclasses, and that a subclass which does not meet these requirements
> > is not a well-defined Java program.
>
> public class Foo {
> private String x;
> public Foo(String x) {
> this.x = x;
> }
> public boolean equals(Object o) {
> if (!(o instanceof Foo)) return false;
> return x.equals(((Foo) o).x);
> }
> public int hashCode() {
> return x.hashCode();
> }
> }
>
> This class is clearly intended to meet the spec of equals() and hashCode()
> and
> does so correctly in the vast majority of cases. But not quite: new
> Foo("").equals(new Foo(null)) is false, but new Foo(null).equals(new
> Foo("")) is
> NPE.
>
> Is this not a well-defined Java class?
AFAICS it isn't: the spec requires equals() to be symmetric for all
non-null x and y:
"for any non-null reference values x and y, x.equals(y) should return
true if and only if y.equals(x) returns true."
The result of any operation that involves this class is therefore not
well-defined, and whatever happens, it's not a bug.
Andrew.