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