0% found this document useful (0 votes)
3 views1 page

Implementing Equals in Java Classes

Implementing an equals method for user-defined types requires care. While it seems simple, using equals with inheritance can violate symmetry. The Date class implements Comparable and defines equals to check that the day, month, and year fields are equal, casting the parameter to Date and checking the class, as equals must accept an Object and check for null values.

Uploaded by

bsitler
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Implementing Equals in Java Classes

Implementing an equals method for user-defined types requires care. While it seems simple, using equals with inheritance can violate symmetry. The Date class implements Comparable and defines equals to check that the day, month, and year fields are equal, casting the parameter to Date and checking the class, as equals must accept an Object and check for null values.

Uploaded by

bsitler
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Implementing equals for user-dened types

Seems easy, but requires some care.


typically unsafe to use equals() with inheritance (would violate symmetry)

public final class Date implements Comparable<Date> { private final int month; private final int day; private final int year; ... public boolean equals(Object y) { if (y == this) return true; if (y == null) return false; if ([Link]() != [Link]()) return false; Date that = (Date) y; if ([Link] != [Link] ) return false; if ([Link] != [Link]) return false; if ([Link] != [Link] ) return false; return true; } }

must be Object. Why? Experts still debate.

optimize for true object equality check for null objects must be in the same class (religion: getClass() vs. instanceof)

cast is guaranteed to succeed check that all significant fields are the same

10

You might also like