zoukankan      html  css  js  c++  java
  • JDK6和JDK7中String的substring()方法及其差异


    1. //
      JDK6,包级私有构造,共享 value数组提升速度 String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; } public String substring(int beginIndex, int endIndex) { // ... 检查边界的代码 // 如果范围和自己一模一样,则返回自身,否则用value字符数组构造一个新的对象 return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); }

        JDK6中value对象不变,只是offset和count 的两个属性值发生了变化 

     
    1.     public String substring(int i, int j)
          {
              if(i < 0)
                  throw new StringIndexOutOfBoundsException(i);
              if(j > value.length)
                  throw new StringIndexOutOfBoundsException(j);
              int k = j - i;
              if(k < 0)
                  throw new StringIndexOutOfBoundsException(k);
              else
                  return i != 0 || j != value.length ? new String(value, i, k) : this;
          }
          public String(char ac[], int i, int j)
          {
              if(i < 0)
                  throw new StringIndexOutOfBoundsException(i);
              if(j <= 0)
              {
                  if(j < 0)
                      throw new StringIndexOutOfBoundsException(j);
                  if(i <= ac.length)
                  {
                      value = "".value;
                      return;
                  }
              }
              if(i > ac.length - j)
              {
                  throw new StringIndexOutOfBoundsException(i + j);
              } else
              {
                  value = Arrays.copyOfRange(ac, i, i + j);
                  return;
              }
          }
          public String(char ac[], int i, int j)
          {
              if(i < 0)
                  throw new StringIndexOutOfBoundsException(i);
              if(j <= 0)
              {
                  if(j < 0)
                      throw new StringIndexOutOfBoundsException(j);
                  if(i <= ac.length)
                  {
                      value = "".value;
                      return;
                  }
              }
              if(i > ac.length - j)
              {
                  throw new StringIndexOutOfBoundsException(i + j);
              } else
              {
                  value = Arrays.copyOfRange(ac, i, i + j);
                  return;
              }
          }

        JDK7中真实地在堆内存中创建了另一个字符数组.

  • 相关阅读:
    关于链表的代码
    c++中的友元函数
    javaweb笔记全套
    包装类、object、单例模式、final、抽象类
    Linux变量内容的删除、代替与替换
    2014年工作中遇到的20个问题:181-200
    Qt中 QString 和int,double等的转换
    jsp学习笔记总结
    工作日志2014-07-04
    Maple入门使用教程
  • 原文地址:https://www.cnblogs.com/luliangliang/p/9067376.html
Copyright © 2011-2022 走看看