Java 具有基本类型的对象整数和原始版本 int。
原始版本更快/更轻/等。所以一般来说你应该使用它们。
我想知道的是,为什么 Java 的设计者不仅拥有对象类型,还使用原始版本作为幕后的优化。
所以:
Integer foo(Integer alpha)
{
Integer total = 0;
for(Integer counter = 0; counter < alpha; counter++)
{
total += counter;
}
return total;
}
将被编译成类似的代码:
int foo(int alpha)
{
int total = 0;
for(int counter = 0; counter < alpha; counter++)
{
total += counter;
}
return total;
}
本质上,这个假设的 Java 编译器会将 Integer、Double、Float 等实例转换为等效的原始类型。只有在真正需要对象的情况下(比如将元素放入容器中)才会涉及实际的 Integer 对象。
注意:上面的代码在 Integer 对象上使用了运算符,我知道这实际上是不允许的。因为我正在发明假设的 Java 编译器,所以我会假装这个编译器对 Integer/Float/Double 有特殊的外壳,就像对 String 一样。