gpt4 book ai didi

java.sql.Timestamp 比较错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:59:23 26 4
gpt4 key购买 nike

<分区>

你好,我有一个这样的代码片段:

Date d1 = new java.sql.Timestamp(new Date().getTime());
Thread.sleep(10);
Date d2 = new java.sql.Timestamp(new Date().getTime());
System.out.println("Date1: " + d1);
System.out.println("Date2: " + d2);
System.out.println("Comparing times d1.t < d2.t: " + (d1.getTime() < d2.getTime()));
System.out.println("Comparing dates d1.before(d2): " + (d1.before(d2)));

输出看起来像这样:

Date1: 2013-03-26 11:04:01.093
Date2: 2013-03-26 11:04:01.103
Comparing times d1.t < d2.t: true
Comparing dates d1.before(d2): false

这个 java.sql.Timestamp 类有什么问题?

是的,我见过这个:

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 a value of type java.util.Date 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.

Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

但它是针对日期 <-> 时间戳关系。

在我的示例中,我只有时间戳,但行为仍然是意外的..

更新:回答

发生这种情况的原因是 before() 方法被重载,而不是在 java.sql.Timestamp 中被覆盖。我期待着“覆盖”行为。比较时间戳的正确方法是使用时间戳变量,而不是日期。

这在 Java 核心中仍然是一个糟糕的设计决策,因为继承应该意味着时间戳是一个日期,没有惩罚和异常(exception)..

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com