I needed to use this method, and after looking at the source code, I noticed a StringBuilder
initialization which is not familar to me (I always use the no-argument constructor from StringBuilder
, i.e. new StringBuilder()
).
In the method:
StringBuilder sb = new StringBuilder(items.size() << 3);
From the JavaDoc:
java.lang.StringBuilder.StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
Why a bit shift is needed here?
Source code:
/** Creates a backslash escaped string, joining all the items. */
public static String join(List<?> items, char separator) {
StringBuilder sb = new StringBuilder(items.size() << 3);
boolean first=true;
for (Object o : items) {
String item = o.toString();
if (first) {
first = false;
} else {
sb.append(separator);
}
for (int i=0; i<item.length(); i++) {
char ch = item.charAt(i);
if (ch=='\\' || ch == separator) {
sb.append('\\');
}
sb.append(ch);
}
}
return sb.toString();
}
Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument.
The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.
Bitshift by 3 means multiplying by 2^3 which is 8. The author must have assumed that each item will take at most 8 characters in the resulting string. Therefore she or he initialized the StringBuilder
with that capacity so it run efficiently. If the assumption is correct StringBuilder
will not reallocate internal structures.
X << 3 means multiply X by 8. In your situation it means to allocate space for 8*list.size() characters. In general you should not care about the implementation details of a class that you are using
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With