Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any chance of Object auto casting to Integer?

Tags:

java

I am wondering whether the below code 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 in some other's PC. What is making it work for me?

like image 935
bighi Avatar asked Oct 16 '15 16:10

bighi


1 Answers

Yes, that's entirely feasible given the way autoboxing is guaranteed to work on small values, and is permitted to work on larger values. For example, this is guaranteed to print true:

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

This might print true, but isn't guaranteed to:

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

I would definitely try not to rely on this in code though, partly because while values in the range of -128 to 127 inclusive are guaranteed to be reused (see JLS 5.1.7), the fact that some JVMs may reuse a wider range of values could lead you into a false sense of security about your code.

In your case, we don't know whether you're seeing a difference in platforms (also bearing in mind that we're talking about Android rather than a JVM) or just that when it "worked" the value being boxed was small, and when it "didn't work" it wasn't.

like image 194
Jon Skeet Avatar answered Oct 13 '22 06:10

Jon Skeet