Java type safe equals()

Viewed 1432

Why is there no type-safe equals() in Java? I would think that would help catching some errors during compile time instead of later runtime error.

As a trivial example consider this:

class Person {
    Integer birthYear;
} 

class Car {
    Long releaseYear;
}

Having a method to take in a Person and collection of Cars and suppose to list all the Cars released in the same year the person was born could end up using:

if (person.birthYear.equals(car.releaseYear)) {
...magic happens...
}

But no magic would ever happen using this. Even if the fields are of same type during the creation of the code, either could be changed at a later point without getting compile error on the comparison code.

What would be best practice to avoid these sort of problems?

1 Answers
Related