java.util.Date equals() doesn't seem to work as expected

后端 未结 3 519
醉话见心
醉话见心 2020-12-18 20:52

Problem

I have a Map, and a list of objects from the database with an effectiveDate property, and I want to check to see

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 21:29

    Part 1: "Shouldn't equals agree with compareTo?*

    No; compareTo should agree with equals, but the reverse is irrelevant.

    compareTo is about sorting order. equals is about equality. Consider race cars, that may be sorted by fastest lap time in practice to determine starting position. Equal lap times does not mean they are the same car.

    Part 2: Equal dates.

    Database calls will return a java.sql.Date, which although it is assignable to java.util.Dare, because it extends that, will not be equal, because the class is different.

    A work around may be:

    java.util.Date test;
    java.sql.Date date;
    if (date.equals(new java.sql.Date(test.getTime()))
    

提交回复
热议问题