当前位置: 代码迷 >> Java相关 >> 关于String 类的理解有关问题
  详细解决方案

关于String 类的理解有关问题

热度:4495   发布时间:2013-02-25 21:49:57.0
关于String 类的理解问题
字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。
帮助文档这说 值 创建之后 不能改变 啥意思啊  


String a="1";
String b ="2";

a=b;
System.out.println(a);
输出之后 还是2 a的值 变了 请问 怎么理解啊

------解决方案--------------------------------------------------------
String a="1";
String b ="2";

String c = a;//a和c都是指向同一个对象

a=b;
//看看c的值是否改变,如果c的值改变,表示String是可变的
System.out.println(a);


如果这个不理解,看这个例子
public class Bean {
 public int num;
}

-----------
Bean a = new Bean();
Bean c = a;
a.num = 9;

//下面看看c.num有没有变
------解决方案--------------------------------------------------------
嗯,我表述的有问题,导致你理解错了,我说的final 不是说final class就不能修改了,而是具体类的构造属性的修饰final,这里面的char value[] ,offset等给你看一下String的源码
Java code
public final class String    implements java.io.Serializable, Comparable<String>, CharSequence{    /** 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(String original) {    int size = original.count;    char[] originalValue = original.value;    char[] v;      if (originalValue.length > size) {         // The array representing the String is bigger than the new         // String itself.  Perhaps this constructor is being called         // in order to trim the baggage, so make a copy of the array.            int off = original.offset;            v = Arrays.copyOfRange(originalValue, off, off+size);     } else {         // The array representing the String is the same         // size as the String, so no point in making a copy.        v = originalValue;     }    this.offset = 0;    this.count = size;    this.value = v;    }}
  相关解决方案