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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With