9 Library methods
This chapter covers
- Problems with
StringBuilder
constructor invocation - Stream API misuse patterns
getClass
() method pitfallsString
-to-boolean
conversion problems- Common mistakes in date and time formatting
- Non-atomic call sequences
In previous chapters, we discussed the pitfalls of using library methods related to numbers, strings, collections, and maps. These are most of the essential parts of the standard library; however, there are other library methods that could be misused but did not fit the previous chapters. We consider these in this chapter.
9.1 Mistake 82: Passing char to StringBuilder constructor
If you use StringBuilder
, you can either provide the initial content or create it empty and append the initial content later:
StringBuilder sb = new StringBuilder("Hello");
The preceding code line is equivalent to
StringBuilder sb = new StringBuilder(); sb.append("Hello");
Well, it’s not strictly equivalent, as the constructor parameter affects the initial size of the inner buffer, so the performance could be slightly different. Still, behaviorally, it’s the same, and many people assume one can safely merge the first append()
into the constructor to save the keystrokes. This may go badly if you start the append
-chain with a char
:
StringBuilder sb = new StringBuilder('['); #1 sb.append(value); sb.append(']');