Is there a chance of automatic casting of objects in Integer?

I am wondering if the code below should work in any scenario?

Object value = attValue.getValue(); // Returns an Object, might contain an Integer if (value instanceof Integer) { if (mAccount.getValue() != value) { // mAccount.getValue() return int // Do something here } } 

It works in my Android studio, but not on some other PC. What makes it work for me?

+5
source share
2 answers

Yes, this is quite feasible, given that the autoblock is guaranteed to work at small values, and it is allowed to work with large values. For example, this is guaranteed to print true:

 Object x = 5; Object y = 5; System.out.println(x == y); 

This may print true, but is not guaranteed:

 Object x = 10000; Object y = 10000; System.out.println(x == y); 

I would definitely try not to rely on this in the code, although partly because when storing values ​​between -128 and 127 inclusive (see JLS 5.1.7 ), the fact that some JVMs can reuse a wider range of values, may lead you to a false understanding of the security of your code.

In your case, we don’t know if you see the difference in the platforms (also having in mind that we are talking about Android, not the JVM) or simply that when it "worked", the value that is inserted into the box was small , and when he "did not work," it was not.

+12
source

You get the same Integer instance since Java 5 had an Integer cache . Because of this cache, you get the same Integer link (you get the same Integer link, and because it has the same link that has the link , which is what == tests). Integer linked cache document says (partially)

Integer objects are cached internally and reused through the same objects that are referenced.

This applies for Integer values ​​in the range of -127 to +127 (maximum Integer value).

This Integer caching only works with autoboxing. Integer objects will not be cached if they are built using the constructor.

+10
source

Source: https://habr.com/ru/post/1233880/


All Articles