首页 > 解决方案 > 创建了多少个对象和引用?

问题描述

我厌倦了下面的代码片段,得到了 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。

这是正确的吗?

标签: javastringobjectheap-memory

解决方案


由于只有三个唯一的变量名,并且每个变量名都是一个引用,所以你是对的,有三个引用。

但是,在 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,但技术上不是同一个对象

*注意:这不适用于 , 等原语intdouble因为.equals()它们不是对象,所以它们没有方法。


推荐阅读