简体   繁体   English

是否有机会将对象自动转换为Integer?

[英]Any chance of Object auto casting to Integer?

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. 它适用于我的Android工作室,但不适用于其他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: 例如,保证打印为true:

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

This might print true, but isn't guaranteed to: 可能打印为true,但不保证:

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. 我肯定会尽量不依赖于代码中的这一点,部分原因是虽然保证重用-128到127(包括-128到127)范围内的值(参见JLS 5.1.7 ),但是一些JVM 可能会重用更广泛的范围值可能会导致您对代码产生错误的安全感。

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. 在你的情况下,我们不知道你是否看到平台上的差异(还要记住我们谈论的是Android而不是JVM),或者只是当它“工作”时,盒装的价值很小,当它“不起作用”时它不是。

You're getting the same Integer instance, since Java 5 there has been an Integer Cache . 您将获得相同的Integer实例,因为Java 5存在整数缓存 Because of that cache, you get the same Integer reference (you're getting the same Integer reference, and because it's the same reference they have reference identity - which is what == tests). 由于该缓存,您获得相同的Integer引用(您获得相同的Integer引用,并且因为它们具有相同的引用,所以它们具有引用标识 - 这就是== tests)。 The linked Integer cache document says (in part) 链接的Integer缓存文档说(部分)

Integer objects are cached internally and reused via the same referenced objects. 整数对象在内部缓存,并通过相同的引用对象重用。

This is applicable for Integer values in range between –127 to +127 (Max Integer value). 这适用于介于-127到+127(最大整数值)范围内的整数值。

This Integer caching works only on autoboxing. 此整数缓存仅适用于自动装箱。 Integer objects will not be cached when they are built using the constructor. 使用构造函数构建整数对象时,它们不会被缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM