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中真实地在堆内存中创建了另一个字符数组.

  • 相关阅读:
    文件上传---普通文件fileupload.jar和url文件httpUrlConnection
    HttpClient学习整理
    编写更少量的代码:使用apache commons工具类库
    多线程进阶
    多线程下HashMap的死循环问题
    线程本地变量ThreadLocal源码解读
    Eclipse工作常见问题总结
    Java集合---ConcurrentHashMap原理分析
    Java集合---Arrays类源码解析
    Java集合---LinkedList源码解析
  • 原文地址:https://www.cnblogs.com/luliangliang/p/9067376.html
Copyright © 2011-2022 走看看