Java's new date () Hashcode () algorithm

Source: Internet
Author: User

Let's look at a simple demo

public class Test_01 {//main watch console output and temperament ... Public    static void Main (string[] args) {        //Run code do you suspect that date and date1 are the same object?        List List = new arraylist<> ();        Date date = new Date ();        List.add (date);        System.out.println (Date.hashcode ());        System.out.println (List.size ());//If you suspect the same object, please add the following demo and try the/*try {new Thread (). Sleep (1);} catch ( Interruptedexception e) {e.printstacktrace ();} *        /Date date1 = new Date ();        List.remove (New Date ());        System.out.println (Date.hashcode ());        System.out.println (List.size ());}    }                

Without the comment of the demo, the output of the two hashcode is the same value, plus the comment after the demo, the output of the two hashcode value is different, have you ever wondered why? It's just that the date class overrides the Equals method and the method of generating hashcode, and the method of generating hashcode in the source code of the date class is as follows

public int hashcode () {        Long ht = This.gettime ();        return (int) HT ^ (int) (HT >> 32);}

The Equals method for comparing two objects in the date source is as follows

public boolean equals (Object obj) {        return obj instanceof Date && getTime () = = ((Date) obj). GetTime ();

See here everyone in the heart should understand why it is such a problem.

The Date class overrides the method of generating the hash code, generating the hash code of the current object with reference to the system time, so if the new date () operation is done at the same time, then the hashcode generated under this operation are equal, Therefore, the value returned in the Equals method overridden by the date class is also true.

Java's new date () Hashcode () algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.