我很困惑为什么 Integer 和 int 可以在 Java 中互换使用,即使一个是原始类型而另一个是对象?
例如:
Integer b = 42;
int a = b;
或者
int d = 12;
Integer c = d;
最佳答案
发表文章的前几句话描述得很好:
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.
简而言之,基本上就是这样。它允许您利用原始数据的集合框架,而无需自己完成工作。
主要的缺点是它会让新程序员感到困惑,如果不能正确理解和使用它,可能会导致困惑/困惑的代码。
关于java - 为什么Integer和int可以互换使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7121581/