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

I may have worked too long in Java without understanding some of its basics.
I understand that == for equality of references to objects, and .equals() for equality of the value of an object.

  • Integers Comparison:

     Integer x = 1, y = 1; System.out.println(x == y); // true 

    Why? Since referential equality of an object is used, it must be false, since they are both different objects.

  • Comparison of getClass() returned values:

     String s1 = "a", s2 = "b"; System.out.println(s1.getClass() == s2.getClass()); // true 

    Why? Again, as mentioned above, an object reference is used. Both using getClass return individual class objects.

Am I missing something or is my mind too tired of coding in Java?

+4
source share
4 answers

Integer Objects

 Integer x = 1, y = 1; System.out.println(x==y); // true, why? 

This is because for values ​​in the byte range (-128 to +127), java uses cached Integer objects stored in the Integer inner class, IntegerCache . Each time an Integer object is created with a value from -128 to +127, the same object will be returned (instead of creating a 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 in the JVM (this is similar to singleton). The class object returned from getClass() each string is the same class object ( String.class ).

+12
source

a is a good question. Because Integer immutable, the Java implementation does not guarantee that you will get a unique object for each integer. Java uses the Integer object pool for small values ​​from -128 to +127, so a and b refer to the same base object 1 .

As with b, both strings are instances of the same String class. getClass() returns the same Class object for each.

0
source

If you do not already know this, this is due to the concept of autboxing / unboxing. So, comparing Integer objects, you can imagine that the compiler automatically adds intValue() when comparing them, so it essentially becomes a primitive value mapping, not an equality of objects.

As for String, this is because it compares the class / types, which is always the only (and therefore the same) in the JVM.

0
source

Your understanding == and equals() correct. In the first case, this is due to caching. In the second case, the class of the object is always the same; it is independent of the instance. If that were the case, it would be a huge waste of memory.

0
source

All Articles