java - Java 中的 String 是如何成为引用类型的?
问题描述
我知道类是引用类型,例如我创建了以下类:
class Class {
String s = "Hello";
public void change() {
s = "Bye";
} }
使用以下代码,我了解这Class
是一个引用类型:
Class c1 = new Class();
Class c2 = c1; //now has the same reference as c1
System.out.println(c1.s); //prints Hello
System.out.println(c2.s); //prints Hello
c2.change(); //changes s to Bye
System.out.println(c1.s); //prints Bye
System.out.println(c2.s); //prints Bye
现在我想用一个字符串做同样的事情,这是行不通的。我在这里做错了什么?:
String s1 = "Hello";
String s2 = s1; //now has the same reference as s1 right?
System.out.println(s1); //prints Hello
System.out.println(s2); //prints Hello
s2 = "Bye"; //now changes s2 (so s1 as well because of the same reference?) to Bye
System.out.println(s1); //prints Hello (why isn't it changed to Bye?)
System.out.println(s2); //prints Bye
解决方案
推荐阅读
- r - “如何有条件地格式化数据表中的字母?
- r - R统计编程:使用magrittr管道将2个参数传递给函数
- kubernetes - 使用 Nginx Ingress 将 TCP 流量发送到入口的命名空间
- if-statement - 不使用带有 Switch 语句的 Else-if 输入 powershell
- r - 为什么我不能将 R x64 中的 memory.limit 设置为 4GB 以上?
- hyperledger-fabric - 关于前端应用程序如何访问超级账本结构中的钱包
- python - 我如何在 django 中注册自定义用户模型(逐一类型)?
- ruby-on-rails - Sidekiq perform_async 与 Apnotic(Apple 推送通知)
- ios - iOS频繁约束常量更新导致帧率下降
- mongodb - 如何在脚本文件中指定 mongodb shell 类型的类型?