在我的Java课程中,教授使用类似的东西:
integerBox.add(new Integer(10));
这和刚做的一样:
integerBox.add(10);
? 我用谷歌搜索了一下,但无法找到一种方式,而且教授含糊不清。 我能找到的最接近的解释是:
int是一个数字;整数是一个可以引用的指针 包含数字的对象。
答案 0 :(得分:6)
基本上,Vector
,ArrayList
,HashMap
等Java集合类不采用基本类型,如int
。
在过去的日子里(Java 5之前),你无法做到这一点:
List myList = new ArrayList();
myList.add(10);
你必须这样做:
List myList = new ArrayList();
myList.add(new Integer(10));
这是因为10
本身只是一个int
。 Integer
是一个包装int
原语的类,而new Integer()
表示你实际上正在创建Integer
类型的对象。在自动装箱出现之前,你不能像在这里那样混合Integer
和int
。
所以外卖是:
integerBox.add(10)
和integerBox.add(new Integer(10))
会将Integer
添加到integerBox
,但这只是因为integerBox.add(10)
透明地创建了Integer
您。两种方式可能不一定以相同的方式创建Integer
,因为使用new Integer
明确创建一个,而自动装箱将使用Integer.valueOf()
。我假设教程使得integerBox
是某种类型的集合(它接受对象,而不是基元)。
但从这个角度来看:
int myInt = 10;
Integer myInteger = new Integer(10);
一个是基元,另一个是Integer
类型的对象。
答案 1 :(得分:5)
integerBox.add(10);
相当于
integerBox.add(Integer.valueOf(10));
因此它可能会返回cached Integer实例。
阅读Java Specialist 191以了解设置自动装箱缓存大小的各种方法。
另请参阅:cache options
答案 2 :(得分:0)
在这种情况下,是的。我假设integerBox是一个对象的集合 - 你只能在integerBox中存储对象。这意味着您不能在集合中具有原始值,例如int。
然而,在Java 5发布之后,出现了一种叫做自动装箱的东西。自动装箱是自动将原始值转换为对象的过程。这是通过其中一个包装类完成的 - Integer,Double,Character等(全部用大写字母和与它们所代表的原始值相关的名称命名)。
当您将int 10添加到集合(最有可能是ArrayList)时,Java VIrtual Machine会在幕后将其转换为Integer类型的对象。