问题
Maybe I've been working too long on Java without really understanding some of its basics.
I do understand that ==
is for object reference equality and .equals()
is for object value equality.
Comparing
Integers
:Integer x = 1, y = 1; System.out.println(x == y); // true
Why? Since object reference equality is used, it should be false since they are both different objects.
Comparing
getClass()
return values:String s1 = "a", s2 = "b"; System.out.println(s1.getClass() == s2.getClass()); // true
Why? Again as per above, object reference is used. Both using
getClass
will return separate Class objects.
Did I miss something or is my mind is too tired of coding in Java?
回答1:
Integer objects
Integer x = 1, y = 1;
System.out.println(x==y); // true, why?
This happens because for values in the byte
range (-128 to +127), java uses cached Integer objects, stored in Integer's inner class, IntegerCache. Every time an Integer object is created with value between -128 and +127, the same object will be returned (instead of creating the new object).
Conversely, for values outside the byte
range, the comparison is false
:
Integer x = 999, y = 999;
System.out.println(x==y); // false
Class objects
String s1 = "a", s2 = "b";
System.out.println(s1.getClass() == s2.getClass()); // true. Why?
This is true because the class of both objects is String
, and there is only one copy of each class object per JVM (it's like a singleton). The class object returned from getClass()
of each String is the same class object (String.class
).
回答2:
a is a good question. As Integer
s are immutable, the Java implementation doesn't guarantee that you will get a unique object for each Integer. Java uses a pool of Integer
objects for small values -128 to +127, so a
and b
both reference the same underlying 1
object.
As for b, both Strings are instances of the same String
class. getClass()
returns the same Class
object for each.
回答3:
If you are not already already aware, this is related to the autboxing/unboxing concept. So, when you compare the Integer
objects , you can imagine the compiler automaticaly adds intValue()
when comparing them - so it essentially becomes a primitive value comparison rather than object equality.
Regarding the String, that;s because it compares class/types, which is always a single (and hence same) one in the JVM.
回答4:
Your understanding of ==
and equals()
is correct. In the first case, it is so because of caching. In the second case, the class of the object is always same, it does not depend on the instance. If it did, it would be huge waste of memory.
来源:https://stackoverflow.com/questions/7464340/why-are-autoboxed-integers-and-getclass-values-equal-not-only-equals-e