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

那么,有什么不同呢?


当前回答

Int是基本数据类型。 Integer是一个包装器类。它可以将int型数据存储为对象。

其他回答

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

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


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

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

使用包装类的原因有很多:

我们得到了额外的行为(例如,我们可以使用方法) 我们可以存储空值,而在原语中则不能 集合支持存储对象,而不支持存储原语。

在Java中,int是一个基本数据类型,而Integer是一个Helper类,它用于将一种数据类型转换为另一种数据类型。

例如:

double doubleValue = 156.5d;
Double doubleObject  = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();

基本数据类型存储最快的可用内存,而Helper类是复杂的,存储在heep内存中。

参考“David Gassner”Java基本训练。

01. 整数可以为空。但是int不能为null。

Integer value1 = null; //OK

int value2 = null      //Error

02. 只能将包装器类类型值传递给任何集合类。

(包装类-布尔,字符,字节,短,整数,长,浮动,双)

List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer  valueInteger = new Integer(value);
element.add(valueInteger);

但通常我们在集合类中添加原始值?02点正确吗?

List<Integer> element = new ArrayList<>();
element.add(5);

是的02是正确的,因为自动装箱。

自动装箱是java编译器进行的自动转换 原始类型与其对应的包装器类之间。

然后5转换为整型值自动装箱。

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.