Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder initialization in Java

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();
  }
like image 323
JohnJohnGa Avatar asked Aug 07 '13 10:08

JohnJohnGa


People also ask

What is the default value for StringBuilder in Java?

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.

How does StringBuilder work in Java?

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.


2 Answers

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.

like image 187
Grzegorz Żur Avatar answered Oct 19 '22 07:10

Grzegorz Żur


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

like image 23
Svetlin Zarev Avatar answered Oct 19 '22 07:10

Svetlin Zarev