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

那么,有什么不同呢?


当前回答

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.

其他回答

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

例如:

int number = 7;

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

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

例如:

Integer number = new Integer(5);

在Java中,'int'类型是一个原语,而'Integer'类型是一个对象。

在c#中,'int'类型与System相同。Int32,是一个值类型(即更像java 'int')。整数(就像任何其他值类型一样)可以被装箱(“包装”)到一个对象中。


对象和原语之间的区别在某种程度上超出了这个问题的范围,但总结一下:

对象为多态性提供了便利,通过引用传递(或者更准确地说,通过值传递引用),并从堆中分配。相反,原语是按值传递的不可变类型,通常从堆栈中分配。

你以前编程过吗? (int)是你可以为变量设置的基本类型之一(就像char, float,…)

但是Integer是一个包装类,你可以使用它对int变量执行一些函数(例如将它转换为字符串或反之亦然,…),但请注意包装类中的方法是静态的,所以你可以随时使用它们,而无需创建Integer类的实例。 回顾一下:

int x;
Integer y; 

x和y都是int类型的变量,但是y是由一个Integer类包装的,并且有几个你使用的方法,但如果你需要调用Integer包装类的一些函数,你可以简单地做到这一点。

Integer.toString(x);

但请注意,x和y都是正确的,但如果您想将它们仅作为基本类型使用,请使用简单形式(用于定义x)。

在java中,根据我的知识,如果你学习那么,当你写在一个;然后在java泛型中,它将编译像Integer a = new Integer()这样的代码。 因此,根据泛型不使用Integer,而是使用int。 所以这是有区别的。

(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...}