bit manipulation - StringBuilder initialization in Java -
i needed use this method, , after looking @ source code, noticed stringbuilder
initialization not familar me (i use no-argument constructor stringbuilder
, i.e. new stringbuilder()
).
in method:
stringbuilder sb = new stringbuilder(items.size() << 3);
from javadoc:
java.lang.stringbuilder.stringbuilder(int capacity)
constructs string builder no characters in , initial capacity specified capacity argument.
why bit shift needed here?
source code:
/** creates backslash escaped string, joining items. */ public static string join(list<?> items, char separator) { stringbuilder sb = new stringbuilder(items.size() << 3); boolean first=true; (object o : items) { string item = o.tostring(); if (first) { first = false; } else { sb.append(separator); } (int i=0; i<item.length(); i++) { char ch = item.charat(i); if (ch=='\\' || ch == separator) { sb.append('\\'); } sb.append(ch); } } return sb.tostring(); }
bitshift 3 means multiplying 2^3 8. author must have assumed each item take @ 8 characters in resulting string. therefore or initialized stringbuilder
capacity run efficiently. if assumption correct stringbuilder
not reallocate internal structures.
Comments
Post a Comment