TIJ: Since String objects are immutable, you can alias to a particular String as many times as you want. Because it’s read-only, there’s no possibility that one reference will change something that will affect the other references. So a read-only object solves the aliasing problem nicely. 因为String是java中经常使用的类,所以TIJ的作者使用String来说明一些特殊类的特性。他称String为Immutable Strings。就是为了说明String等类与绝大多数object的不同。可能我的用语有时不太确切。 无论是final,还是String等类,都是java的特性。与面向对象理论并不等同
但是String对象类型除外,每次都会new出一个新的String对象,赋值的时候是数值复制
------------------------------------------------------------------------------每次都是new新的吗?试试这段代码:
String str1 = new String("A");//注意这里不是String str1 = "A"; String str2 = str1; if (str1 == str2) {
System.out.println("same address");
} else {
System.out.println("different address");
}每次new新的是说String是不可变的,而不是不可多引用的
String str1 = "A";
String str2 = "A";
结果也是str1 == str2我觉得String str2 = str1并不是地址赋值,是数值复制。String与其他object不同。
intern() 为每个独一无二的字符顺序都产生一个(而且只有一个)String句柄
一旦有必要改变原来的内容, 每个String方法都小心地返回了一个新的String对象。
若内容不需要改变, 则方法只返回指向原来那个String的一个句柄。
这样做可以节省存储空间和系统开销。
我赞成这种观点:
“我觉得String str2 = str1并不是地址赋值,是数值复制“
我个人理解之所以出现地址看似相同,是因为String class 重载了 == 运算符
Since String objects are immutable, you can alias to a particular String as many times as you want. Because it’s read-only, there’s no possibility that one reference will change something that will affect the other references. So a read-only object solves the aliasing problem nicely.
因为String是java中经常使用的类,所以TIJ的作者使用String来说明一些特殊类的特性。他称String为Immutable Strings。就是为了说明String等类与绝大多数object的不同。可能我的用语有时不太确切。
无论是final,还是String等类,都是java的特性。与面向对象理论并不等同
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我给你举例子说明String是传递引用,你却引一段关于immutable Strings说“就是想说明,即使多个String实例指向同一个地址,但是改变了其中任何一个的值,并不会影响其他的值”如果“不是传递引用”哪来的“多个String实例指向同一个地址”
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
既然你自己都不清楚自己再说什么,我不再和你讨论了
TO:zfd (稻草人) 很明显,String 和其他的对象类是一样的,是传递的引用。只是java的引用和C的指针不太一样。这和String、Integer、Long等的immutable(不可变)是两回事。
操作任何object都是使用reference。但是不同object之间有差异。TIJ使用immutable object来区分普通的object。
【当然这可能只是TIJ的叫法,不过我觉得很形象。】
immutable object的所有操作都会返回一个同型对象,不会改变原始对象的内容。
看你这么“形容”上面的话了!!!
还有,String的重载运算符有+和+=,不是只有+
--------------------------------------------------------------------------------
String是对象