栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java不垃圾回收内存

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java不垃圾回收内存

制作子字符串时, 您的子字符串会保留对原始字符串的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不再存在此问题。具有较新版本的人没有此问题。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573821.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号