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