当引用类型相同时 - 数组
When Reference Types Are the Same - Arrays
我在看JavaSE 6 specs,后来做了个小测试,解决一些疑惑
Two reference types are the same run-time type if:
- They are both class or both interface types, are defined by the same class loader, and have the same binary name (§13.1), in which case they are sometimes said to be the same run-time class or the same run-time interface.
- They are both array types, and their component types are the same run-time type (§10).
运行 下面的代码...
public class Test {
public static void main(String[] args) {
String str = "" + new String(" ");
String[] strArr = {str};
String[] strArr2 = {str};
System.out.println("strArr == strArr2 : " + (strArr == strArr2));
}
}
...我期待以下输出:
strArr == strArr2 : true
但是当前输出是:
strArr == strArr2 : false
我错过了什么?
仅仅因为它们是同一类型,并不意味着它们是同一对象。
当你这样做时
String[] strArr = {str};
String[] strArr2 = {str};
您正在创建两个包含相同内容的数组,但数组本身是两个独立的对象。
它们是同一类型(字符串数组)但它们不是同一对象(引用 X 和引用 Y)。当您说 strArr == strArr2
时,您是在询问它们是否是同一个对象(或者实例,如果您更喜欢该术语)。
您引用的 JLS 与您所说的不同,它只是说 String[]
和 String[]
是同一类型。
您正在比较数组引用。
你的strArr
和strArr2
引用显然不一样。
您可以使用 Arrays.equals(strArr, strArr2)
比较值。
如果您使用值 strArr
初始化 strArr2
,您的参考比较将成立。
此外,比较数组类型 (strArr.getClass() == strArr2.getClass()
) 无论哪种方式都适用。
总结:
引用类型String[]
与引用类型String[]
相同,即
strArr.getClass() == strArr2.getClass() // true
String[]
的实例 strArr
与同一类型的另一个实例 strArr2
不同,即
strArr == strArr2 // false
我在看JavaSE 6 specs,后来做了个小测试,解决一些疑惑
Two reference types are the same run-time type if:
- They are both class or both interface types, are defined by the same class loader, and have the same binary name (§13.1), in which case they are sometimes said to be the same run-time class or the same run-time interface.
- They are both array types, and their component types are the same run-time type (§10).
运行 下面的代码...
public class Test {
public static void main(String[] args) {
String str = "" + new String(" ");
String[] strArr = {str};
String[] strArr2 = {str};
System.out.println("strArr == strArr2 : " + (strArr == strArr2));
}
}
...我期待以下输出:
strArr == strArr2 : true
但是当前输出是:
strArr == strArr2 : false
我错过了什么?
仅仅因为它们是同一类型,并不意味着它们是同一对象。
当你这样做时
String[] strArr = {str};
String[] strArr2 = {str};
您正在创建两个包含相同内容的数组,但数组本身是两个独立的对象。
它们是同一类型(字符串数组)但它们不是同一对象(引用 X 和引用 Y)。当您说 strArr == strArr2
时,您是在询问它们是否是同一个对象(或者实例,如果您更喜欢该术语)。
您引用的 JLS 与您所说的不同,它只是说 String[]
和 String[]
是同一类型。
您正在比较数组引用。
你的strArr
和strArr2
引用显然不一样。
您可以使用 Arrays.equals(strArr, strArr2)
比较值。
如果您使用值 strArr
初始化 strArr2
,您的参考比较将成立。
此外,比较数组类型 (strArr.getClass() == strArr2.getClass()
) 无论哪种方式都适用。
总结:
引用类型String[]
与引用类型String[]
相同,即
strArr.getClass() == strArr2.getClass() // true
String[]
的实例 strArr
与同一类型的另一个实例 strArr2
不同,即
strArr == strArr2 // false