原始类型和包装类之间的主要区别是什么?
问题描述:
这两行之间有什么区别?
What is the difference between these two lines?
int pInt = 500;
和
Integer wInt = new Integer(pInt);
或
Integer wInt = new Integer(500);
答
无。
这是完全相同的事情。在第一种情况下,你只有一个补充变量。
That's the exact same thing. In the first case you just have a supplementary variable.
注意 autoboxing 你很少需要同时拥有 int
和 Integer
变量。所以对于大多数情况来说这就够了:
Note that with autoboxing you rarely need to have both an int
and an Integer
variables. So for most cases this would be enough :
int pInt = 500;
整数有用的主要情况是区分变量未知的情况(即 null
):
The main case where the Integer would be useful is to distinguish the case where the variable is not known (ie null
) :
Integer i = null; // possible
int i = null; // not possible because only Object variables can be null
但是不要保留两个变量,一个是够了。
But don't keep two variables, one is enough.