java - 创建了多少个对象和引用?
问题描述
我厌倦了下面的代码片段,得到了 3 个对象和 3 个引用的答案。但在答案键中说它是 4 个对象和 3 个引用。如果我错了或答案键,我会感到困惑。请有人帮忙。
String str1=new String("Java"); //line 1
String str2=new String("GFT"); //line 2
String str3=str1; //line 3
str1=str1.concat(str2); //line 4
str3=str2.toUpperCase(); //line 5
我的答案的解释:
参考文献:str1、str2、str3。所以引用数= 3。
对象:最初创建的对象计数 = 0。
- 第 1 行创建具有值“Java”和引用“str1”的新对象。对象创建计数 = 1。
- 第 2 行创建具有值“GFT”和引用“str2”的新对象。对象创建计数 = 2。
- 第 3 行创建新引用 "str3" ,它不创建新对象,它指向第 1 行 (str1) 中创建的对象。
- 第 4 行创建了值为“JavaGFT”的新对象,str1 现在指向该对象。对象创建计数 = 3。
- 第 5 行有一个值“GFT”,因为它已经存在 str3 现在指向由 str2 创建的对象,因为 str2 是使用 new 运算符创建的。(我验证了 str2==str3 是否返回 true)所以最后创建的对象 count=3,引用计数=3。
这是正确的吗?
解决方案
由于只有三个唯一的变量名,并且每个变量名都是一个引用,所以你是对的,有三个引用。
但是,在 Java(和许多其他语言)中,字符串是不可变的,这意味着对字符串的任何操作都会返回一个全新的字符串。
您的误解似乎与String.toUpperCase()
. 如果字符串已经完全大写,那么这将返回一个与原始字符串相等的新字符串。您可以对此进行测试:
String strA = "ABC";
String strB = strA.toUpperCase();
// two objects that are technically different, though they look and act the same as each other
print(strA == strB); // false - they are not the same string
print(strA.equals(strB)); // true - however, they are equal to each other
在 Java 中,这对任何 Object * 都成立——==
检查将比较两个引用的内存位置,true
如果它们都指向内存中的相同位置,则返回。同时,.equals()
可以为对象定制行为。如果没有被覆盖,则返回到==
检查,但 String 会覆盖该行为并true
在字符串相同时返回。
因此,总共创建了四个对象:
new String("Java")
new String("GFT")
str1.concat(str2)
str2.toUpperCase()
// 等同于str2
,但技术上不是同一个对象
*注意:这不适用于 , 等原语int
,double
因为.equals()
它们不是对象,所以它们没有方法。
推荐阅读
- javascript - @Output childEvent 未初始化
- sql - 是否有脚本可以为单元格公式绕过 50000 个字符?
- c - 为什么 valgrind 报告未初始化的值错误?
- python - 用 celery 运行线程模块;守护进程不允许有子进程
- javascript - 如何在 ASP.NET 核心 Web 应用程序中禁用客户端验证?
- python - 使用 Tensorflow 格式化具有可变时间步长的 LSTM 层的输入
- python - discord.py 重写 | 为我的命令出错
- php - 从 blob 重建 jpg
- javascript - 如何使用 Material-UI 将多个 TextField 元素放入 Grid 容器中?
- android - webview中base64图像的低分辨率