为什么人们仍然在Java中使用原始类型? [英] Why do people still use primitive types in Java?

查看:350
本文介绍了为什么人们仍然在Java中使用原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从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.

我最近看到很多新的Java项目(肯定需要至少版本5的JRE,如果不是6)正在使用 int 而不是 java.lang.Integer ,尽管使用后者要方便得多,因为它有一些转换为 long values等的辅助方法。

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 ==)

for 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

EDIT Why does (3) return true and (4) return false?

因为它们是两个不同的对象。最接近零的256个整数[-128; 127]由JVM缓存,因此它们返回相同的对象。但是,超出该范围,它们不会被缓存,因此会创建一个新对象。为了使事情变得更复杂,JLS要求缓存至少 256个flyweights。如果他们愿意,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中使用原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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