New SimpleDateFormat always returns the same link for a given date


I tried to replicate the error using the same instance of SimpleDateFormat for multiple threads. However, I ran into another problem and did not find any answers on it.

This simple block of code replicates the problems that I see.

DateFormat d1 = new SimpleDateFormat("ddMMyyyy"); DateFormat d2 = new SimpleDateFormat("ddMMyyyy"); DateFormat d3 = new SimpleDateFormat("ddMMyy"); System.out.println("d1 = " + d1); System.out.println("d2 = " + d2); System.out.println("d3 = " + d3); 

The results of these operations under java 7 (1.7_0_21) are as follows

 d1 = java.text.SimpleDateFormat@c5bfbc60 d2 = java.text.SimpleDateFormat@c5bfbc60 d3 = java.text.SimpleDateFormat@b049fd40 

As you can see, although I am creating new objects for d1 and d2, they eventually become the same reference. d3 ends up being a new instance since the pattern is different.

Does java compile / run-time this optimization? Any pointers would be helpful

+8
java
source share
3 answers

SimpleDateFormat and DateFormat ( SimpleDateFormat superclass), and Format ( DateFormat superclass) is implemented toString() , therefore, toString() from the Object class is executed, the code of which is:

 public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } 

Now SimpleDateFormat hashCode is generated:

 public int hashCode() { return pattern.hashCode(); // just enough fields for a reasonable distribution } 

This means that if you create multiple instances of SimpleDateFormat with the same pattern as in your case, they will have the same hashCode , and therefore toString() will return the same for these cases.

Also, since it was spotted by rixmath, instances of SimpleDateFormat with the same pattern will also be equal.

+14
source share

SimpleDateFormat actually implements hashCode by returning the hash code of the template.

You can check if there are actually different objects using System.identityHashCode() :

 System.out.println("d1 = " + d1 + " / " + System.identityHashCode(d1)); System.out.println("d2 = " + d2 + " / " + System.identityHashCode(d2)); System.out.println("d3 = " + d3 + " / " + System.identityHashCode(d3)); 

This will print 3 different values.

+6
source share

These are different instances, try this

  DateFormat d1 = new SimpleDateFormat("ddMMyyyy"); DateFormat d2 = new SimpleDateFormat("ddMMyyyy"); System.out.println(d1 == d2); 

he prints

 false 

as for the same java.text.SimpleDateFormat@c5bfbc60 , they are based on the class name and hashCode. According to the Object.hashCode API, it does not necessarily return individual values ​​for individual objects.

+5
source share

All Articles