Comparing primitive to wrapper object with == behaviour unexplained

只谈情不闲聊 提交于 2019-11-29 10:53:45

问题


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);
}

Output:

true
true
false

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

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


回答1:


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.

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.

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




回答2:


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

Since one is primitive and another is a wrapper class of it, unboxing happens and primitive comparison takes place (==).

Whereas:

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

is an Object comparison. Different instances are getting compared so == won't work in this case.




回答3:


Charcter class is not singleton, so always a new object will be creating when calling the contructor and new objects refer to their respective references.So (c == cy) gives you false




回答4:


it's obvious why the last comparision gives false: both Characters are explicitly initialized with new, thus being different objects

why the first two comparisions give true, however, is only partly clear: the char value is definitely used to retrieve a pre-stored Character instance, but I don't know how exactly the pre-defined Character objects are mapped to this pre-stored instance

I would expect, though, it works like "=="-comparision for String objects: if at compile time one of the compared instances is a pre-stored Character then the compiler inserts a call to equals() replacing the "=="-comparision



来源:https://stackoverflow.com/questions/36544223/comparing-primitive-to-wrapper-object-with-behaviour-unexplained

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!