Two StringBuilder​ constructors that take String or CharSequence argument throw a confusing NegativeArraySizeException if the argument is extremely large.
This is because the constructor tries to set the initial capacity equal to the length of the argument + 16 (this is specified in the spec, actually).
When the argument's length is > (Integer.MAX_VALUE - 16), the initial capacity becomes negative due to the integer overflow.
public class T {
public static void main(String[] args) {
// 0, 1 -> cannot create str
// 2, ..., 15 -> confising NegativeArraySizeException
// 16, 17 -> OOM in StringBuilder
// 18 and more -> Ok
int DELTA = 10;
String str = "Z".repeat(Integer.MAX_VALUE - DELTA);
StringBuilder sb = new StringBuilder(str);
}
}
It would be more accurate to throw OutOfMemoryError in such cases.
This is because the constructor tries to set the initial capacity equal to the length of the argument + 16 (this is specified in the spec, actually).
When the argument's length is > (Integer.MAX_VALUE - 16), the initial capacity becomes negative due to the integer overflow.
public class T {
public static void main(String[] args) {
// 0, 1 -> cannot create str
// 2, ..., 15 -> confising NegativeArraySizeException
// 16, 17 -> OOM in StringBuilder
// 18 and more -> Ok
int DELTA = 10;
String str = "Z".repeat(Integer.MAX_VALUE - DELTA);
StringBuilder sb = new StringBuilder(str);
}
}
It would be more accurate to throw OutOfMemoryError in such cases.
- duplicates
-
JDK-8029784 (str) StringBuilder and StringBuffer fail when initialized with large strings
- Closed
- relates to
-
JDK-8219409 Clarify capacity of StringBuffer/StringBuilder near Integer.MAX_VALUE
- Open
-
JDK-8221430 StringBuffer(CharSequence) constructor truncates when -XX:-CompactStrings specified
- Closed