A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 悦鹏 中级黑马   /  2015-6-14 21:43  /  364 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

String的不可变性和toString的可变性该怎么证明?

1 个回复

倒序浏览
第一个问题,看String类的源代码可以理解一点。
String 使用 final修饰的 是不可以继承的。也就无法覆盖。
---------------------------------------------------------------------------------------------------------------
JDK中的说明:
String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。
字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。例如:

     String str = "abc";
等效于:

     char data[] = {'a', 'b', 'c'};     String str = new String(data);

---------------------------------------------------------------------------------------------
你翻译一下第一句注释
The value is used for character storage.
value字符数组是用来存放字符数据的.
据我观察这个 value字符数组就是用来存放 字符串的数组。
定义是使用的 private final修饰的,就是不可变的。

这是String类的源代码
  1. public final class String
  2.     implements java.io.Serializable, Comparable<String>, CharSequence
  3. {
  4.     /** The value is used for character storage. */
  5.     private final char value[];
  6. /** The offset is the first index of the storage that is used. */ //偏移(offset)是存储空间使用的第一个索引
  7.     private final int offset;

  8.     /** The count is the number of characters in the String. *///count 是字符串中字符们的数量.
  9.     private final int count;
  10.     public String() {
  11.         this.offset = 0;
  12.         this.count = 0;
  13.         this.value = new char[0];
  14.     }

  15.     public String(String original) {
  16.         int size = original.count;//大小等于传入的字符串大小
  17.         char[] originalValue = original.value;//char[] 原value=原字符串.value
  18.         char[] v;//新的字符数组 v
  19.           if (originalValue.length > size) {//如果字符数组长度 大于 字符串长度size
  20.             // The array representing the String is bigger than the new
  21.             // String itself.
  22. // Perhaps this constructor is being called
  23.             // in order to trim the baggage, so make a copy of the array.
  24.             int off = original.offset;//偏移
  25.             v = Arrays.copyOfRange(originalValue, off, off+size);//数组复制(原字符数组,偏移,偏移+大小)
  26.         } else {
  27.             // The array representing the String is the same
  28.             // size as the String, so no point in making a copy.
  29.             v = originalValue;
  30.         }
  31.         this.offset = 0;
  32.         this.count = size;
  33.         this.value = v;//字符串对象自己的value等于传入的 原字符串的字符数组 进行判断修改后的 v
  34.     }
复制代码

第二个问题
toString是Object类中的方法
[size=-1]String
toString()
          返回该对象的字符串表示。
类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。
所有类都继承这个toString()方法。
你可以覆盖它,所以它返回的字符串是根据你的需要定制的。

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马