java.sql.Timestamp的equals违反了对称性

JDK 文档说明:
  • Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn't an instance of java.sql.Timestamp, because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.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.”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值