集合中只能存放引用,不能存放基本类型。
As any Java programmer knows, you can't put an int
(or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer
in the case of int
). When you take the object out of the collection, you get the Integer
that you put in; if you need an int
, you must unbox the Integer
using the intValue
method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter
集合中存放的可都是对象的引用,实际内容都在堆上面或者方法区里面,但是基本数据类型是在栈上分配空间的。随时就被收回的。但是通过自动包装类就可以把基本类型转为对象类型,存放引用就解决了这个问题。