Duplicate :
|
|
Relates :
|
|
Relates :
|
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.
|