java吧 关注:1,246,407贴子:12,722,907
  • 2回复贴,共1

String构造函数的一个问题

取消只看楼主收藏回复

String对象一旦创建就不能修改
源码:
Public String(char value[]){
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Array.copyOf(value,size); // 这里,Array.copyOf()的内部实现是借助System.arraycopy()方法
}
最后一行为啥不写成this.value = value而是通过复制呢?
我的初步理解是,如果是写成this.value = value,那当修改value数组,就等于修改了String对象,这恰恰是违背String对象一旦创建就不能修改的设计原则。而使用arraycopy的话,就遵循不变的原则,因为我已经复制了一份,若value改变了,已经是一个新的String对象。有点凌乱!大家的看法如何?


1楼2014-05-05 15:10回复
    想想。。以上我这么想也不对。。。


    3楼2014-05-05 15:17
    收起回复
      JAVA String类源码定义截取:
      public final class String{
      /** The value is used for character storage. */
      private final char value[];
      /** The offset is the first index of the storage that is used. */
      private final int offset;
      /** The count is the number of characters in the String. */
      private final int count;
      其中一个构造器
      public String(char value[]) {
      int size = value.length;
      this.offset = 0;
      this.count = size;
      this.value = Arrays.copyOf(value, size);问题就是这里,为啥不能用this.value = value直接赋值,而是用复制数组方式赋值?
      }

      @zhou686269


      6楼2014-05-05 15:48
      收起回复