gpt4 book ai didi

java - 理解 Java 中对象比较的 == 运算符

转载 作者:行者123 更新时间:2023-12-01 08:59:04 25 4
gpt4 key购买 nike

我知道 == 运算符会检查相等的引用(地址),但是在比较 Thread 时,我不知道编译器如何抛出以下错误和 String目的。java: incomparable types: java.lang.Thread and java.lang.String这是我的代码:

public static void main(String[] args) {
Thread t = new Thread();
Object o = new Object();
String s = new String("");

System.out.println(t == o);//no issues here

System.out.println(t==s);// but this throws above error
}
为什么允许比较 ThreadObject但不是 ThreadString ?

最佳答案

指定比较不能在它们之间转换的引用类型必须导致编译错误。见 JLS chapter 15.21.3 :

15.21.3. Reference Equality Operators == and !=

[...]

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).

关于java - 理解 Java 中对象比较的 == 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62922178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com