我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。

那么,有什么不同呢?


当前回答

int变量保存一个32位有符号整数值。Integer(大写I)保存对(类)类型Integer或null对象的引用。

Java自动在两者之间进行类型转换;当Integer对象作为int操作符的参数出现,或者被赋值给int变量,或者一个int值被赋值给Integer变量时,从Integer到int。这种类型转换称为装箱/解装箱。

如果一个引用null的Integer变量被显式或隐式地解盒,则抛出NullPointerException异常。

其他回答

Int用于声明原始变量

e.g. int i=10;

Integer用于创建类Integer的引用变量

Integer a = new Integer();

在Java和c#中,int和Integer是用来表示不同事物的两个不同术语。它是可以赋值给可以精确存储的变量的基本数据类型之一。每次只声明其类型的一个值。

例如:

int number = 7;

其中int是赋给值为7的变量number的数据类型。所以int型只是一个原语,不是一个对象。

而Integer是具有静态方法的基元数据类型的包装类。That可以用作需要对象的方法的参数,其中as int可以用作需要整数值的方法的参数,可用于算术表达式。

例如:

Integer number = new Integer(5);

在c#中,int只是System的别名。Int32,系统的字符串。字符串,double for System。双等等……

我个人更喜欢int, string, double等,因为他们不需要使用系统;这是个愚蠢的理由,我知道……

(Java版本) 简单来说,int是原始的(不能有空值),Integer是int的包装对象。

一个使用Integer和int的例子,当你想比较int变量时,它会抛出错误。

int a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is wrong - cannot compare primitive to null
{
do something...}

Instead you will use,
Integer a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is correct/legal
{ do something...}

int is a primitive datatype whereas Integer is an object. Creating an object with Integer will give you access to all the methods that are available in the Integer class. But, if you create a primitive data type with int, you will not be able to use those inbuild methods and you have to define them by yourself. But, if you don't want any other methods and want to make the program more memory efficient, you can go with primitive datatype because creating an object will increase the memory consumption.