I needed to use this method , and, looking at the source code, I noticed the StringBuilder initialization, which is not familiar to me (I always use the constructor without arguments from StringBuilder , i.e. new StringBuilder() ).
In the method:
StringBuilder sb = new StringBuilder(items.size() << 3);
From JavaDoc:
java.lang.StringBuilder.StringBuilder (int capacity)
Creates a string builder with no characters in it, and the initial capacity specified by the capacity argument.
Why is a bit shift needed here?
Source:
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(); }
source share