开发者

Why are autoboxed Integers and .getClass() values ==-equal, not only .equals()-equal?

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.

  1. 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 d开发者_如何学Goifferent objects.

  2. 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?


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


a is a good question. As Integers 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜