简体   繁体   English

Java:将Int存储在Integer数组中

[英]Java: Store int in Integer array

Can you store int values into a Integer array? 您可以将int值存储到Integer数组中吗?

Given an array: 给定一个数组:

Integer[] array = new Integer[10];

Are the following two statements equivalent? 以下两个语句是否等效?

Integer x = new Integer(1);
array[0] = x;

int x = 1;
array[0] = x;

They are not 100% equivalent. 它们不是100%等效的。 The following should be equivalent however: 但是,以下内容应等效:

Integer x = Integer.valueOf(1); 
array[0] = x;

int x = 1; 
array[0] = x;

Note that the int primitive gets autoboxed to the Integer wrapper class. 请注意,int原语会自动装箱到Integer包装器类。 So you're not storing an int primitive in the Integer array, but an Integer object. 因此,您不是在Integer数组中存储int原语,而是在Integer对象中存储。

You should hardly ever use the Integer constructor (which always creates a new object) but use one of its static factory methods or autoboxing (less code), which allow to cache instances (since they are immutable). 您几乎不应该使用Integer构造函数(始终创建一个新对象),而应使用其静态工厂方法或自动装箱(较少代码)中的一种,它们可以缓存实例(因为它们是不可变的)。

Once the values are inside the array itself, they are both values of type Integer . 一旦这些值位于数组本身内部,它们都是Integer类型的值。 If you pass a primitive object to an instance of its wrapper class, then that primitive type is autoboxed , meaning its automatically converted to the type of its wrapper class. 如果将原始对象传递给其包装器类的实例,则该原始类型将被自动装箱 ,这意味着其将自动转换为其包装器类的类型。

Integer x = 4; //autoboxing: "4" is converted to "new Integer(4)"

Likewise, a wrapper class type can is unboxed when it is passed to a primitive type: 同样,包装器类类型可以在传递给原始类型时取消装箱

int x = new Integer(4); //unboxing: "new Integer(4)" is converted to primitive int 4

For your purposes, both examples your wrote will work. 为了您的目的,您编写的两个示例都可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM