我厌倦了下面的代码片段,得到了 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。
这样对吗?
答案 0 :(得分: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 中,这适用于任何对象* - ==
检查将比较两个引用的内存位置,如果它们都指向内存中的相同位置。同时,true
可以为对象定制行为。如果未被覆盖,则返回到 .equals()
检查,但 String 会覆盖该行为并在字符串相同时返回 ==
。
所以,总共创建了四个对象:
true
new String("Java")
new String("GFT")
str1.concat(str2)
// 与 str2.toUpperCase()
相同,但技术上不是同一个对象*注意:这不适用于 str2
、int
等原语,它们没有 double
方法,因为它们不是对象。