制作子字符串时, 您的子字符串会保留对原始字符串的char数组的引用
(此优化可以非常快速地处理字符串的许多子字符串)。因此,当您将子字符串保留在
al列表中时,就将整个文件保留在内存中。为避免这种情况,请使用将字符串作为参数的构造函数创建一个新的String。
所以基本上我建议你
while(in.hasNextLine()) { String s = in.nextLine(); al.add(new String(s.substring(0,1))); // extracts first 1 character }
String(String)构造函数的源代码明确指出其用法是减少“行李”:
164 public String(String original) { 165int size = original.count; 166char[] originalValue = original.value; 167char[] v; 168if (originalValue.length > size) { 169 // The array representing the String is bigger than the new 170 // String itself. Perhaps this constructor is being called 171 // in order to trim the baggage, so make a copy of the array. 172 int off = original.offset; 173 v = Arrays.copyOfRange(originalValue, off, off+size); 174} else { 175 // The array representing the String is the same 176 // size as the String, so no point in making a copy. 177 v = originalValue; 178} 179this.offset = 0; 180this.count = size; 181this.value = v;
更新: OpenJDK 7 Update 6不再存在此问题。具有较新版本的人没有此问题。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)