读 String原代码

1.  CharSequence接口定义了一个只读的char序列。String 实现 CharSequence , Serializable , Comaprable<String>


2.  由 char[] value, int offset, int count 和 int hash组成。


3.  构造函数 public String(String original) 基本上来说是没用的,因为String本身是immutable的,没必要copy一下。但有一个用处:节省空间。比如说,你用subString生成的一个String,它是重用原来的char[]的,而原来的那个String你已经不想用了(这个条件很重要), 你可以用这个构造函数重建一个String来释放空间。

Java代码 复制代码 收藏代码
  1. public String(String original) {   
  2.         int size = original.count;   
  3.         char[] originalValue = original.value;   
  4.         char[] v;   
  5.         if (originalValue.length > size) {   
  6.             // The array representing the String is bigger than the new   
  7.             // String itself.  Perhaps this constructor is being called   
  8.             // in order to trim the baggage, so make a copy of the array.   
  9.             int off = original.offset;   
  10.             v = Arrays.copyOfRange(originalValue, off, off+size);   
  11.         } else {   
  12.             // The array representing the String is the same   
  13.             // size as the String, so no point in making a copy.   
  14.             v = originalValue;   
  15.         }   
  16.         this.offset = 0;   
  17.         this.count = size;   
  18.         this.value = v;   
  19.     }  
 

 

posted on 2013-02-14 19:18  蜜雪薇琪  阅读(224)  评论(0编辑  收藏  举报