JDK 文档说明:
-
Note: This type is a composite of a
java.util.Date
and a separate nanoseconds value. Only integral seconds are stored in thejava.util.Date
component. The fractional seconds - the nanos - are separate. TheTimestamp.equals(Object)
method never returnstrue
when passed an object that isn't an instance ofjava.sql.Timestamp
, because the nanos component of a date is unknown. As a result, theTimestamp.equals(Object)
method is not symmetric with respect to thejava.util.Date.equals(Object)
method. Also, thehashCode
method uses the underlyingjava.util.Date
implementation and therefore does not include nanos in its computation.
java.util.Date
date
=
new
java.util.Date();
java.util.Date
stamp
=
new
java.sql.Timestamp(
date
.getTime());
assertTrue(
date
.equals(
stamp
));
assertFalse(
stamp
.equals(
date
));
assertFalse(
date
.compareTo( stamp) == 0);
assertTrue(
stamp
.compareTo(
date
) == 0);
java.sql.Timestamp对java.util.Date进行了扩展,并增加了nanoseconds域。但由于equals违反了对称性,所以Timestamp和Date不能应用于同一集合。
Timestamp的这种实现是个错误,不值得效仿。
Effective Java对此有说明:While there is no satisfactory way to extend an instantiable class and add a value component,there is a fine workaround.
Follow the advice of Item 16, “Favor
composition over inheritance.”