问题
Does StringBuilder have a limit of characters for maximum capacity in JAVA.
StringBuilder url=new StringBuilder();
stmt = connnection.createStatement();
String sql="SOME QUERY";
rs = stmt.executeQuery(sql);
while(rs.next())
{
String emailId=rs.getString("USER_EMAIL_ID");
url.append(emailId);
}
does StringBuilder variable 'url' have a maximum capacity, or it can hold everything?
回答1:
Yes, it has limitation in capacity of max integer which 2147483647(technically).
StringBuilder
internally holds chracters in char[] object, and array has limitation in size. read more about it on other thread
回答2:
If you go through with this link this may clear you more Oracle Docs String Builder Buffer Capacity
Now you want to declare the Capacity of any StringBuilder Class, then one Constructor StringBuilder(int initCapacity)
is defined for this.
StringBuilder(int initCapacity)
:- Creates an empty string builder with the specified initial capacity.
Here because of parameter as int
the maximum capacity that a StringBuilder
Class can is reach will be 2147483647
.
there are various method regarding this context of Capacity in StringBuilder
Class, those methods also consider the parameters of type int
.
void setLength(int newLength) :- Sets the length of the character sequence. If newLength is less than length(), the last characters in the character sequence are truncated. If newLength is greater than length(), null characters are added at the end of the character sequence.
void ensureCapacity(int minCapacity) :- Ensures that the capacity is at least equal to the specified minimum.
these methods also takes argument as of int
type . So, Using these methods or contructors you will able to generate a object with max capacity of 2147483647
.
回答3:
Java 9 introduced JEP 254: Compact Strings. This allows storing strings more space-efficiently by storing characters in a byte array. If all characters are Latin 1, one byte is used per char, otherwise two bytes per char are used.
So the answer is: If compact strings are enabled (the default) and your StringBuilder
contains only Latin 1 chars, the maximum size is Integer.MAX_VALUE
*, otherwise it is Integer.MAX_VALUE / 2
*.
* Or slightly less, see "Do Java arrays have a maximum size?"
来源:https://stackoverflow.com/questions/38067717/how-many-characters-can-a-java-stringbuilder-hold