将原语与包装器对象进行比较,其中==行为无法解释 [英] Comparing primitive to wrapper object with == behaviour unexplained

查看:144
本文介绍了将原语与包装器对象进行比较,其中==行为无法解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段我需要理解的代码:

I have a piece of code which I need to understand:

public static void main(String[] args) {
    Character c = new Character('a');
    Character cy = new Character('a');
    char cx = 'a';

    System.out.println(c == cx);
    System.out.println(cx == cy);
    System.out.println(c == cy);
}

输出:

true
true
false

我无法理解为什么只有第三个陈述失败。

I am unable to understand why only the third statement is failing.

编辑:这个问题与 .equals vs == 这是关于原始与对象比较的问题。

This question is different to the .equals vs == question as this about primitive versus object comparison.

推荐答案

c cy 引用字符的不同实例 class(每次调用构造函数时,都会创建一个新实例),因此比较这些引用会返回 false

c and cy refer to different instances of the Character class (each time you invoke a constructor, you create a new instance), so comparing these references returns false.

另一方面,当您将它们中的任何一个与原始 cx 进行比较时,它们将被取消装箱到 char ,并且 char 比较返回true。

On the other hand, when you compare either of them to the primitive cx, they are unboxed to char, and the char comparison returns true.

您使用过 Character.valueOf('a' )而不是新字符('a'),你会在两个电话中得到相同的实例,并且引用比较将返回 true (因为 valueOf 返回缓存的字符实例,如果参数< = 127)。

Had you used Character.valueOf('a') instead of new Character('a'), you would have gotten the same instance in both calls, and the reference comparison would have returned true (since valueOf returns a cached Character instance if the argument <= 127).

这篇关于将原语与包装器对象进行比较,其中==行为无法解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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