gpt4 book ai didi

java - 为什么可以在 Java 中通过引用来比较不兼容的类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:15 25 4
gpt4 key购买 nike

看看这个片段:

    List<Integer> c = new ArrayList<>();
Map<String,Boolean> m = new HashMap<>();
if( c == m ) //no error here! WHY?
{
c = m; //"Incompatible types" error, as expected.
m = c; //"Incompatible types" error, as expected.
}

c == m 为什么没有报错?

我使用的是 jdk1.8.0.20 的 javac,我没有理由怀疑它无视 java 语言规范,所以这在规范中具有相当绝对的确定性,所以:

规范允许这样的事情有什么意义/目的/用处?

最佳答案

仅仅因为类型不可转换并不意味着它们不是相等的对象。如果类型是“不可转换的”,则意味着需要强制转换来检查类型实际上是否可转换。

interface Outputer extends Consumer<String>, Serializable { }

Outputer out = System.out::println;
Consumer<String> cs = out;
Serializable s = out;
System.out.println(s == cs); // prints true

// s = cs; // Inconvertible types, doesn't compile
s = (Serializable) cs; // compiles and runs fine.

css 是不可转换的类型,但它们指向同一个对象并且打印 true

关于java - 为什么可以在 Java 中通过引用来比较不兼容的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28768397/

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