使用==检查对象引用相等(在Java中) [英] checking object reference equality using == (in Java)

查看:125
本文介绍了使用==检查对象引用相等(在Java中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么......

    String a = new String("a");
    StringBuilder b = new StringBuilder("a");
    System.out.println(a==b);

...在编译时会导致类型不兼容错误......

... result in an incompatible types error when compiling given that...

    String a = new String("b");
    Object b = new StringBuilder("b");
    System.out.println(a==b);

...不是吗?

为什么我可以比较String和Object的对象引用,但不能比较StringBuilder和String?它们不仅仅是内存位置的地址吗?

Why can I compare the object references of a String and an Object but not a StringBuilder and a String? Aren't they all just addresses to memory locations?

谢谢

推荐答案

根据Java语言规范(15.21.3):

Acording to the Java Language Specification (15.21.3):


如果无法转换,则是编译时错误通过转换转换(§5.5)为另一种类型的操作数类型。两个操作数的运行时值必然是不相等的(忽略两个值都为空的情况)。

It is a compile-time error if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal (ignoring the case where both values are null).

这意味着,为了比较两种引用类型,应该能够将其转换为另一种引用类型。 String是一个对象,但 String StringBuilder 之间没有强制转换。

Which means, in order to "compare" two reference types, one should be able to be cast to the other. String "is" an object, but there is no "cast" between String and StringBuilder.

这篇关于使用==检查对象引用相等(在Java中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆