Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Overriding Object.equals in Generic class

843793Apr 9 2007 — edited Jan 22 2009
Hello all!

I'm finding the erasure feature of Java Generics to be a total pain. It appears that I cannot create an overridden version of the Object.equals (Object) method that returns true if, and only if:

1. The supplied object reference is not null.
2. The supplied object reference has the same type as the generic type. (This seems to be impossible.)
3. This object and the supplied object have the same values.

For example,
public class MeasurementUnit {
    // ...
}
public final class Distance extends MeasurementUnit {
    // ...
}
public final class Velocity extends MeasurementUnit {
    // ...
}
// etc.
public class Measurement <UnitType extends MeasurementUnit> {
    private double measurement;
    // ...
    public Measurement (double value) {
        this.measurement = value;
    }
    @Override
    public boolean equals (Object obj) {
        // Null references are not equal to this instance.
        if (obj == null) {
            return false;
        }
        // Only measurement types of the same type can equal.  Sadly, Java generics only
        // let us verify that obj is a Measurement.
        if (!obj.getClass ().equals (Measurement.class)) {
            return false;
        }
        // Determine if both objects have the same data.  Requires an unchecked cast.
        Measurement <UnitType> other = (Measurement <UnitType>) obj;  // Unchecked cast.
        return this.measurement == other.measurement;
    }
    // ...
}
public class Test {
    public static void main (String []) {
        Measurement <Distance> someLength = new Measurement <Distance> (5.0);
        Measurement <Velocity> someVelocity = new Measurement <Velocity> (5.0);
        if (someLength.equals (someVelocity)) {
            System.out.println ("It didn't work!  Velocities and distances are equal????");
        }
        else {
            System.out.println ("It worked!  Velocities and distances cannot be equal!!!!");
        }
    }
}
Have a guess which string would be output? Yup! The wrong one!

Is there any way around this, or does erasure ensure that Java can never give the right answer to this problem?

Mike

Message was edited by:
MikeAllen
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 19 2009
Added on Apr 9 2007
66 comments
1,155 views