我重新作了测试 如果 String s = "xxxx..."; // 1 数据长度大于65535就会出错char[] c = new char[123456]; ... String s = new Stirng(c); // 2 数值再大也不出错。我查了JDK的String类的sourceCode如下: 1使用的构造方法如下: public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { // The array representing the String is bigger than the new // String itself. Perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. v = new char[size]; System.arraycopy(originalValue, original.offset, v, 0, size); } else { // The array representing the String is the same // size as the String, so no point in making a copy. v = originalValue; } this.offset = 0; this.count = size; this.value = v; }2. 构造方法如下: public String(char value[]) { int size = value.length; char[] v = new char[size]; System.arraycopy(value, 0, v, 0, size); this.offset = 0; this.count = size; this.value = v; } 这两个构造方法都是把数据String or char[] 转化赋值给自己的char[] value 为什么出问题,我也解释不清楚,等待高手答复。
如果可用内存不足,自然会出现OutOfMemoryError可以通过java命令的 -Xmx参数来制定允许JVM使用的最大Heap大小(记得默认是64M来着)。例如,允许JVM使用的最大heap改为512MB,命令如下
java -Xmx512m className
//没那么大。
我只想说明String的大小不是受程序限制,而是其它外界原因的限制(内存,时间等)。
String 源代码里有个长度的变量65535个字符最多.
再多就用流吧
如果
String s = "xxxx..."; // 1 数据长度大于65535就会出错char[] c = new char[123456];
...
String s = new Stirng(c); // 2 数值再大也不出错。我查了JDK的String类的sourceCode如下:
1使用的构造方法如下:
public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
v = new char[size];
System.arraycopy(originalValue, original.offset, v, 0, size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}2. 构造方法如下: public String(char value[]) {
int size = value.length;
char[] v = new char[size];
System.arraycopy(value, 0, v, 0, size);
this.offset = 0;
this.count = size;
this.value = v;
}
这两个构造方法都是把数据String or char[] 转化赋值给自己的char[] value
为什么出问题,我也解释不清楚,等待高手答复。
当然如果你配给jvm的heapsize小,还没到int值,就已经outofmemoryto blackpark:
jvm缺省heapsize在64m左右。 需要调整heapsize大小