How many characters can a Java StringBuilder hold?

♀尐吖头ヾ 提交于 2019-12-01 15:00:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!