Differences between new Integer(123), Integer.valueOf(123) and just 123

前端 未结 5 1974
野的像风
野的像风 2020-12-01 06:45

Recenlty I saw code (Java) like this:

myMethod(new Integer(123));

I am currently refactoring some code, and there is a tip in Sonar tool, t

5条回答
  •  -上瘾入骨i
    2020-12-01 06:46

    Does your method require an int or an Integer?

    new Integer(int) and Integer.valueOf(int) both return Integer objects, but valueOf should be preferred as it is more efficient because it returns cached objects. If your method requires an Integer you should use Integer.valueOf.

    If your method requires an int, you should use an int (e.g. 123).

    However, it is not strictly necessary to match types in this way because of autoboxing, which automatically converts an int to an Integer and vice versa when the types don't match. This allows you to pass an int into a method requiring an Integer, and an Integer into a method requiring an int. But be aware that there are performance costs associated with autoboxing. The most common example of when you would use autoboxing is if you wanted to store primitives in a collection.

提交回复
热议问题