java 比较Java中的int和Object
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3815598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare int and Object in Java
提问by user
I have the following code:
我有以下代码:
Object obj = 3;
//obj.equals(3); // so is this true?
Does obj
equal to 3?
不obj
等于3?
回答by Mark Peters
What's at play here is autoboxing.
这里的作用是自动装箱。
When you use a primitive literal when a reference is expected, the primitive is autoboxedto the wrapper type (in this case from int to Integer).
当您在需要引用时使用原始文字时,原始文字将自动装箱为包装器类型(在本例中从 int 到 Integer)。
Your code is the equivalent of this:
您的代码相当于:
Object obj = Integer.valueOf(3);
if ( obj.equals(Integer.valueOf(3)) ) {
//...
I'll leave it to you to decide whether that's true or not.
我会让你来决定这是不是真的。
回答by OscarRyz
This is also interesting:
这也很有趣:
Object t = 3;
t.equals( 3 ); // true
3 == t; // true
But
但
Object h = 128;
h.equals( 128 ); // true
128 == h; // false
.equals
will work, becase the value will be compared. ==
Will work, using the references, but only from -128 to 127, because the autoboxing mechanism, uses an internal pool to hold "most commonly used" references.
.equals
会起作用,因为将比较该值。==
可以使用引用,但只能从 -128 到 127,因为自动装箱机制使用内部池来保存“最常用”的引用。
Strange enough: o == 3
will fail at compile time.
很奇怪: o == 3
会在编译时失败。
回答by jjnguy
Yes.
是的。
Here is what's happening behind the scenes.
这是幕后发生的事情。
Object obj = Integer.valueOf(3);
obj.equals(Integer.valueOf(3));
So, of course they are equal.
所以,当然他们是平等的。
回答by mikera
The first statement will set obj to be a automatically boxed Integer (the same as Integer.valueOf(3))
第一条语句将 obj 设置为一个自动装箱的 Integer(与 Integer.valueOf(3) 相同)
Hence the second statement will return true.
因此,第二个语句将返回 true。
回答by parag.rane
You need to do Type-casting here to achieve the task
您需要在此处进行类型转换才能完成任务
Object obj = 3; if(obj.equals(Integer.valueOf(3))) { // to do something.... }