新Integer(123),Integer.valueOf(123)和123之间的差异 [英] Differences between new Integer(123), Integer.valueOf(123) and just 123

查看:812
本文介绍了新Integer(123),Integer.valueOf(123)和123之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Recenlty我看到这样的代码(Java):

Recenlty I saw code (Java) like this:

myMethod(new Integer(123));

我目前正在重构一些代码,Sonar工具中有一个提示,它对内存更友好使用这样的事情:

I am currently refactoring some code, and there is a tip in Sonar tool, that it's more memory friendly to use sth like this:

myMethod(Integer.valueOf(123));

但是在这种情况下,我认为如果我使用的话没有区别:

However in this case, I think that there is no difference if I would use:

myMethod(123);

我能理解,如果我将变量传递给方法,但硬编码为int?或者如果有Long / Double等,我想要长数字表示。但整数?

I could understand that, if I would pass a variable to the method, but hard coded int? Or if there would be Long/Double etc and I want Long representation of number. But integer?

推荐答案

new Integer(123)将创建一个新的对象每次调用的实例。

new Integer(123) will create a new Object instance for each call.

根据 javadoc Integer.valueOf(123)有区别对象...所以如果你多次调用它,你可能(或可能不会)最终得到相同的对象

According to the javadoc, Integer.valueOf(123) has the difference it caches Objects... so you may (or may not) end up with the same Object if you call it more than once.

例如,以下代码:

   public static void main(String[] args) {

        Integer a = new Integer(1);
        Integer b = new Integer(1);

        System.out.println("a==b? " + (a==b));

        Integer c = Integer.valueOf(1);
        Integer d = Integer.valueOf(1);

        System.out.println("c==d? " + (c==d));

    }

具有以下输出:

a==b? false
c==d? true

至于使用 int 值,你正在使用原始类型(考虑到你的方法也在其签名上使用原始类型) - 它将使用更少的内存并且可能更快,但是你不会将它添加到集合中,例如。

As to using the int value, you are using the primitive type (considering your method also uses the primitive type on its signature) - it will use slightly less memory and might be faster, but you won't be ale to add it to collections, for instance.

另请参阅Java的 AutoBoxing 如果您的方法的签名使用 Integer - 使用它时,JVM将自动调用 Integer.valueOf()为你(因此也使用缓存)。

Also take a look at Java's AutoBoxing if your method's signature uses Integer- when using it, the JVM will automatically call Integer.valueOf() for you (therefore using the cache aswell).

这篇关于新Integer(123),Integer.valueOf(123)和123之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆