jdk1.8 java.util.Date 的equals的坑

原文链接: https://my.oschina.net/sglz1993/blog/1922301

一句话:java的Date比较请不要用equals方法。

背景说明:某对象有一个java.util.Date的属性,但是从数据库查封装的对象是java.sql.Timestamp,原因很简单,直接看源码

java.util.Date:

public boolean equals(Object obj) {
    return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
public int compareTo(Date anotherDate) {
    long thisTime = getMillisOf(this);
    long anotherTime = getMillisOf(anotherDate);
    return (thisTime 

java.sql.Timestamp extends  java.util.Date

public boolean equals(java.lang.Object ts) {
  if (ts instanceof Timestamp) {
    return this.equals((Timestamp)ts);
  } else {
    return false;
  }
}
public int compareTo(java.util.Date o) {
   if(o instanceof Timestamp) {
        // When Timestamp instance compare it with a Timestamp
        // Hence it is basically calling this.compareTo((Timestamp))o);
        // Note typecasting is safe because o is instance of Timestamp
       return compareTo((Timestamp)o);
  } else {
        // When Date doing a o.compareTo(this)
        // will give wrong results.
      Timestamp ts = new Timestamp(o.getTime());
      return this.compareTo(ts);
  }
}

        java.sql.Timestamp 的equals 只能比较java.sql.Timestamp对象,但compareTo对java.util.Date进行了适配,或者直接用getTime进行比较也是一样

转载于:https://my.oschina.net/sglz1993/blog/1922301

你可能感兴趣的:(jdk1.8 java.util.Date 的equals的坑)