小编eth*_*tad的帖子

java.util.Date equals()似乎没有按预期工作

问题

我有一个Map<Date, Foo>,以及一个带有effectiveDate属性的数据库对象列表,我想检查一下Date我的地图中的键是否effectiveDate与数据库中的任何一个相同- 如果是这样的话,那么就做Foo.

代码看起来像这样:

for (Bar bar : databaseBars) {
  Foo foo = new Foo();
  if (dateMap.containsKey(bar.getEffectiveDate()) {
    foo = dateMap.get(bar.getEffectiveDate());
  }
  // do stuff with foo and bar
}
Run Code Online (Sandbox Code Playgroud)

然而,dateMap.containsKey即使我确定它有时存在,但是调用总是返回false.

调查

作为一个完整性检查,我打印出了日期的长值,以及equals()通话和compareTo()通话的结果:

for (Date keyDate : dateMap.keySet()) {
  if (keyDate == null) {
    continue; // make things simpler for now
  }

  Date effDate = bar.getEffectiveDate();

  String template = "keyDate: %d; effDate: %d; …
Run Code Online (Sandbox Code Playgroud)

java date

15
推荐指数
1
解决办法
1万
查看次数

标签 统计

date ×1

java ×1