Skip to content

Instantly share code, notes, and snippets.

@ccare
Created Oct 19, 2012
Embed
What would you like to do?
Example of Timestamp breaking the symmetric contract Object.equals()
...
/*
You would normally expect .equals() to be Symmetric (see [1] ). This is
documented (see [2]) and has presumably been implemented this way for
good reasons. However, if you don't know you have an instance of
java.util.Timestamp (which is a specialisation of java.util.Date),
then this can be an interesting gotcha.
[1] http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)
[2] http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#equals(java.lang.Object)
*/
@Test
public void testTimestampEquality() {
final Date date = new Date();
final long epochTime = date.getTime();
final Timestamp timestamp = new Timestamp(epochTime);
Assert.assertTrue(date.equals(timestamp));
Assert.assertFalse(timestamp.equals(date));
}
...
@ccare

This comment has been minimized.

Copy link
Owner Author

@ccare ccare commented Oct 19, 2012

You would normally expect .equals() to be Symmetric (see [1] ). This is documented (see [2]) and is presumably implemented this way for good reasons. However, if you don't know you have an instance of java.util.Timestamp (which is a specialisation of java.util.Date), then this can be an interesting gotcha.

[1] http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)
[2] http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#equals(java.lang.Object)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment