new SimpleDateFormat always returns same reference for a given dateFormat

前端 未结 3 625
暗喜
暗喜 2021-01-17 22:41


I was trying to replicate a bug by using the same instance of SimpleDateFormat across multiple threads. However I got stuck with another problem and did not find any

相关标签:
3条回答
  • 2021-01-17 23:29

    SimpleDateFormat nor DateFormat (SimpleDateFormat superclass) nor Format (DateFormat superclass) have a toString() implemented, so the toString() from the Object class is actually executed, whose code 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
    }
    

    Which means that if you create numerous SimpleDateFormat instances with the same pattern, like in your case, they will have the same hashCode and hence toString() will return the same for these instances.

    Moreover, as it has been spotted by rixmath, SimpleDateFormat instances with the same pattern will also be equal.

    0 讨论(0)
  • 2021-01-17 23:40

    SimpleDateFormat actually implements hashCode by returning the hashcode of the pattern.

    You can verify that there are actually distinct objects by 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.

    0 讨论(0)
  • 2021-01-17 23:43

    They are different instances, try this

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

    it prints

    false
    

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

    0 讨论(0)
提交回复
热议问题