zoukankan      html  css  js  c++  java
  • java-substring

    1 String x = "abcdef";
    2 x = x.substring(1,3);
    3 System.out.println(x);//输出bc

    来看jdk6中String的substring

     1 //JDK 6
     2 //该构造器非公开
     3 String(int offset, int count, char value[]) {
     4     this.value = value;
     5     this.offset = offset;
     6     this.count = count;
     7 }
     8  
     9 public String substring(int beginIndex, int endIndex) {
    10     //check boundary
    11     return  new String(offset + beginIndex, endIndex - beginIndex, value);
    12 }

     jdk6中substring确实新创建了一个String对象,但问题在于该对象的char[] value字段仍然是旧String对象的(新瓶装旧酒),设想如果就string很长,新string很短,这就造成了内存泄漏

    一种解决方法

    x = x.substring(x, y) + ""//最终会创建新的char[]

    再来看jdk7的substring

     1 //JDK 7
     2 //其实在jdk6中就有该构造器,只不过substring未调用
     3 public String(char value[], int offset, int count) {
     4     //check boundary
     5     this.value = Arrays.copyOfRange(value, offset, offset + count);//一份全新的拷贝
     6 }
     7  
     8 public String substring(int beginIndex, int endIndex) {
     9     //check boundary
    10     int subLen = endIndex - beginIndex;
    11     return new String(value, beginIndex, subLen);
    12 }

    参考:https://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/

  • 相关阅读:
    【go语言】Windows下go语言beego框架安装
    分页
    MongoDB用户与权限管理
    MongoDB安装在Centos7下安装
    centos7安装mysql5.7.33 tar包方式
    文件路径分隔符
    python之批量打印网页为pdf文件
    Python驱动SAP GUI完成自动化(五)
    动态内存与智能指针
    关联容器
  • 原文地址:https://www.cnblogs.com/holoyong/p/7507865.html
Copyright © 2011-2022 走看看