问题描述
从 Java 5 开始,我们已经对原始类型进行装箱/拆箱,以便将 int
包装为 java.lang.Integer
,等等.
Since Java 5, we've had boxing/unboxing of primitive types so that int
is wrapped to be java.lang.Integer
, and so and and so forth.
我最近看到很多使用 int
而不是 java.lang.Integer
,虽然使用后者更方便,因为它有一些帮助方法可以转换为 long
值等.
I see a lot of new Java projects lately (that definitely require a JRE of at least version 5, if not 6) that are using int
rather than java.lang.Integer
, though it's much more convenient to use the latter, as it has a few helper methods for converting to long
values et al.
为什么有些仍然在 Java 中使用原始类型?有什么切实的好处吗?
Why do some still use primitive types in Java? Is there any tangible benefit?
推荐答案
在 Joshua Bloch 的 Effective Java,第 5 项:避免创建不必要的对象",他发布了以下代码示例:
In Joshua Bloch's Effective Java, Item 5: "Avoid creating unnecessary objects", he posts the following code example:
public static void main(String[] args) {
Long sum = 0L; // uses Long, not long
for (long i = 0; i <= Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
运行需要 43 秒.将 Long 放入原语将其缩短到 6.8 秒......如果这能说明我们为什么使用原语的话.
and it takes 43 seconds to run. Taking the Long into the primitive brings it down to 6.8 seconds... If that's any indication why we use primitives.
缺少本机值相等也是一个问题(.equals()
与 ==
相比相当冗长)
The lack of native value equality is also a concern (.equals()
is fairly verbose compared to ==
)
对于 biziclop:
for biziclop:
class Biziclop {
public static void main(String[] args) {
System.out.println(new Integer(5) == new Integer(5));
System.out.println(new Integer(500) == new Integer(500));
System.out.println(Integer.valueOf(5) == Integer.valueOf(5));
System.out.println(Integer.valueOf(500) == Integer.valueOf(500));
}
}
结果:
false
false
true
false
为什么 (3) 返回 true
和 (4) 返回 false
?
Why does (3) return true
and (4) return false
?
因为它们是两个不同的对象.最接近零的 256 个整数 [-128;127] 由 JVM 缓存,因此它们返回相同的对象.但是,超出该范围时,它们不会被缓存,因此会创建一个新对象.更复杂的是,JLS 要求缓存至少 256 个享元.JVM 实现者可以根据需要添加更多内容,这意味着这可以在缓存最近的 1024 并且所有这些都返回 true 的系统上运行...... #awkward
Because they are two different objects. The 256 integers closest to zero [-128; 127] are cached by the JVM, so they return the same object for those. Beyond that range, though, they aren't cached, so a new object is created. To make things more complicated, the JLS demands that at least 256 flyweights be cached. JVM implementers may add more if they desire, meaning this could run on a system where the nearest 1024 are cached and all of them return true... #awkward
这篇关于为什么人们仍然在 Java 中使用原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!