Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

Why does java.sql.Timestamp extend java.util.Date

When I saw this I got baffled:

  public class 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 hashCode() {
        return super.hashCode();
    }

It is indeed documented with a bold Note (see https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html)

What could be the cause to make such a, to me, very bad decision? Why not call super.equals(this) when compared to a java.util.Date object to make the equal comparison symmetrical?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead, use java.time

As others stated:

  • This class inheritance is poor design, a flawed hack.
  • Now moot, as this class is now legacy, supplanted by java.time.Instant.

Avoid all the old legacy date-time classes found outside the java.time package.

For databases, use a driver compliant with JDBC 4.2 or later to directly exchange java.time objects with your database. You can forget all about java.sql.Timestamp.

Storing:

Instant instant = Instant.now() ;
myPreparedStatement.setObject( … , instant ) ;

Retrieving:

Instant instant = myResultSet.getObject( … , Instant.class ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...