Search code examples
javasimpledateformat

Why Jdk DateFormat use StringBuffer instead of StringBuilder?


I checked Jdk19 source code and I noticed that DateFormat always uses StringBuffer when formatting a Date into String. Shouldn't that be StringBuilder because it's faster?


Solution

  • It's because at the time when DateFormat was written (Java 1.1) there was no class StringBuilder (which only exists since Java 1.5).

    If the StringBuffer was an implementation detail this would be no problem.

    But DateFormat has two methods that accept and return a StringBuffer:

    Rewriting these methods to accept and return a StringBuilder would break existing code.


    Please note that (as Johannes Kuhn has pointed out) the first of these two methods is specified by the abstract base class java.text.Format (also from Java 1.1), so changing this would have even greater implications.