为什么Integer和int可以互换使用? [英] Why can Integer and int be used interchangably?

查看:368
本文介绍了为什么Integer和int可以互换使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么Integer和int可以在Java中互换使用,即使一个是基本类型而另一个是对象?

I am confused as to why Integer and int can be used interchangeably in Java even though one is a primitive type and the other is an object?

例如:

Integer b = 42;
int a  = b;

int d = 12;
Integer c = d;


推荐答案

发表文章的前几句话描述得很漂亮好吧:

The first few sentences of the posted article describe it pretty well:


您不能将int(或其他原始值)放入集合中。集合只能保存对象引用,因此必须将原始值装入适当的包装类(在int的情况下为Integer)。当您从集合中取出对象时,您将获得放入的Integer;如果需要int,则必须使用intValue方法取消对Integer的装箱。所有这些装箱和拆箱都是一种痛苦,并使你的代码变得混乱。自动装箱和拆箱功能可自动完成整个过程,消除痛苦和杂乱。

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.

这基本上就是简单的说法。它允许您利用收集框架来获得灵感,而无需自己完成工作。

That is basically it in a nutshell. It allows you take advantage of the Collections Framework for primatives without having to do the work yourself.

主要的缺点是它会混淆新的程序员,并且可能导致混乱/如果不能正确理解和使用代码会造成混淆。

The primary disadvantage is that it confuses new programmers, and can lead to messy/confusing code if it's not understood and used correctly.

这篇关于为什么Integer和int可以互换使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆