For example, let's say you ask what is the difference between
String
and StringBuffer
. Easy enough, they respond: String
cannot be changed while StringBuffer
can be.Then I ask why they think Java is designed this way. The C++ STL has only one type for instance, called
string
(or wstring
), and it is mutable. So why did Gosling and Steele choose to use two classes?You would not believe the number of candidates with 10 years of experience who cannot answer this question: they look at me puzzled, not knowing what to do. And I am really trying to help them. "Just don't think about strings, what advantage can you see for immutable objects in general? In a multi-threading context for instance?" Sometimes the best answer I can get is that "it helps with performance" but without any details.
I actually don't know the details about Guy Steele's decision, but any answer like these would work:
- Immutable objects are thread-safe by definition.
- Strings are often used as keys in hash tables, so it is interesting to have an immutable string (otherwise you would need to copy the keys).
- You can save memory by sharing the character array between different String instances (the
String.intern()
method).
No comments:
Post a Comment