Java中的Integer和int有什么区别? [英] What is the difference between Integer and int in Java?

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

问题描述

例如,你为什么可以这样做:

  int n = 9; 

但不能:

  Integer n = 9; 

您可以:

  Integer.parseInt(1); 

但不是:

  int.parseInt(1); 


解决方案

int 是一个原始类型。类型 int 的变量存储要表示的整数的实际二进制值。 int.parseInt(1)没有意义,因为 int 不是 一个类,因此没有任何方法。



整数是一个类, Java语言。类型变量存储引用 Integer 对象,就像任何其他引用对象)类型。 Integer.parseInt(1)是从类调用静态方法 parseInt Integer (注意,这个方法实际上返回一个 int ,而不是 Integer )。 / p>

更具体地说, Integer 是一个类型为 int 。这个类用于需要 int 像任何其他对象一样处理,例如在通用类型或需要可空性的情况下。



请注意,Java中的每个基本类型都有一个等效的 wrapper 类:




  • code> byte 有字节

  • short

  • Integer

  • long Long li>
  • boolean 布尔

  • code> char 字符

  • float Float

  • double Double



包装器类继承自Object类,而原语不继承。因此,它可以用于对象引用或与泛型集合。



因为java 5我们有自动装箱,原始和包装类之间的转换是自动完成的。当心,因为这可以引入微妙的错误和性能问题;明确表示转换永远不会伤害。


For example why can you do:

int n = 9;

But not:

Integer n = 9;

And you can do:

Integer.parseInt("1");

But not:

int.parseInt("1");

解决方案

int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods.

Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).

To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.

Note that every primitive type in Java has an equivalent wrapper class:

  • byte has Byte
  • short has Short
  • int has Integer
  • long has Long
  • boolean has Boolean
  • char has Character
  • float has Float
  • double has Double

Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.

Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.

这篇关于Java中的Integer和int有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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