java - 为什么Integer和int可以互换使用?

标签 java autoboxing

我很困惑为什么 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/

相关文章:

java - 使用 JPanel 的 JFrame 布局

java - 首选项中的 ListView

java - 使用自定义 View 中的共享元素启动 Activity

java - 自动装箱对原始包装器 ArrayList 的性能影响

java - JVM 是否优化了不必要的自动装箱?

java - 在 Java 中递归列表的正确方法是什么?

java:从类中查找项目名称

Java 自动装箱和数学表达式?

java - 为什么包装类对象的标识符不能用作引用变量

java - 内部编译器错误 ArrayIndexOutOfBoundsException : -1 . ..generateUnboxingConversion