何时使用原语和Java中的引用类型 [英] When to use primitive and when reference types in Java

查看:116
本文介绍了何时使用原语和Java中的引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪种情况下,您应该使用原始类型( int )还是引用类型( Integer )?

In which case should you use primitive types(int) or reference types (Integer)?

这个问题引起了我的好奇心。

This question sparked my curiosity.

推荐答案


在哪种情况下你应该使用原始的
类型( int )或引用类型
整数)?

根据经验,我将使用原语(例如 int ),除非我必须使用包装原语的类。

As a rule of thumb, I will use a primitive (such as int) unless I have to use a class that wraps a primitive.

其中一个案例是必须使用包装类,例如 Integer 是否使用泛型,因为Java不支持使用原始类型作为类型参数:

One of the cases were one must use a wrapper class such as Integer is in the case of using generics, as Java does not support the use of primitive types as type parameters:

List<int> intList = new ArrayList<int>();               // Not allowed.
List<Integer> integerList = new ArrayList<Integer>();   // Allowed.

而且,在很多情况下,我会利用自动装箱和拆箱,所以我不必显式执行从基元到其包装器的转换类,反之亦然:

And, in many cases, I will take advantage of autoboxing and unboxing, so I don't have to explicitly perform conversions from primitives to its wrapper class and vice versa:

// Autoboxing will turn "1", "2", "3" into Integers from ints.
List<Integer> numbers = Arrays.asList(1, 2, 3); 

int sum = 0;

// Integers from the "numbers" List is unboxed into ints.
for (int number : numbers) {
  sum += number;
}

另外,作为附加说明,从基元转换为其包装类对象时,并且不需要对象的唯一实例,使用包装器方法提供的 valueOf 方法,因为它执行缓存并返回相同的实例以获取特定值,从而减少数量创建的对象:

Also, as an additional note, when converting from primitives to its wrapper class objects, and unique instances of objects are not necessary, use the valueOf method provided by the wrapper method, as it performs caching and return the same instance for a certain value, reducing the number of objects which are created:

Integer i1 = Integer.valueOf(1);   // Prefer this.
Integer i2 = new Integer(1);       // Avoid if not necessary.

有关 valueOf 方法的更多信息, <$ c的API规范$ c> Integer.valueOf 方法可以作为这些方法在基元的包装类中的行为的参考。

For more information on the valueOf methods, the API specification for the Integer.valueOf method can serve as a reference for how those methods will behave in the wrapper classes for primitives.

这篇关于何时使用原语和Java中的引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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