zoukankan      html  css  js  c++  java
  • Subtring方法在JDK6 和JDK7

    1, subtring在JDK6中:

    String是有字符数组组成的,在JDK6中,String 类包含3个属性,char value[], int offset, int count. 它们被用作存储真正的字符数组,数组的第一个索引,String中字符的个数。

    当调用substring()方法时,将创建一个新的字符串,但是字符串的值仍旧是指向堆中相同的字符数组,这两个字符串所不同的是他们的count和offset的值。

    下面的代码简单的并且之包含重点的解释这这个问题。

    //JDK 6
    String(int offset, int count, char value[]) {
        this.value = value;
        this.offset = offset;
        this.count = count;
    }
     
    public String substring(int beginIndex, int endIndex) {
        //check boundary
        return  new String(offset + beginIndex, endIndex - beginIndex, value);
    }

    2, JDK6中substring方法存在的问题。

    如果你有一个非常长的字符串,但是你仅仅需要这个字符串的一小部分,然而使用substring时,这将导致性能问题,既然你只想要一小部分,你却保存了这个thing。在JDK6中,使用如下的解决方案解决这个问题:

    x = x.substring(x, y) + ""

    3,JDK7中substring方法

    在JDK7中substring得到了改进,substring方法实际上在堆中创建了一个新的字符数组。

    //JDK 7
    public String(char value[], int offset, int count) {
        //check boundary
        this.value = Arrays.copyOfRange(value, offset, offset + count);
    }
     
    public String substring(int beginIndex, int endIndex) {
        //check boundary
        int subLen = endIndex - beginIndex;
        return new String(value, beginIndex, subLen);
    }

     

     

  • 相关阅读:
    SqlServer数据库同步方案详解(包括跨网段)
    makefile 和shell文件相互调用
    处理百万级以上的数据处理
    makefile Template(添加多个lib)
    Linux下如何删除非空目录
    makefile Template
    g++ 编译和链接
    gcc include路径
    C++ XML解析之TinyXML篇
    利用Lucene.net搭建站内搜索(2)分词技术
  • 原文地址:https://www.cnblogs.com/zhonghan/p/3675744.html
Copyright © 2011-2022 走看看