我在阅读更多Joel关于软件的内容时,看到Joel Spolsky提到了一种特定类型的程序员需要知道Java/C#(面向对象编程语言)中int
和Integer
之间的区别。
那么,这两者有什么区别呢?
我在阅读更多Joel关于软件的内容时,看到Joel Spolsky提到了一种特定类型的程序员需要知道Java/C#(面向对象编程语言)中int
和Integer
之间的区别。
那么,这两者有什么区别呢?
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);
但通常我们将基本类型的值添加到集合类中吗?第二点正确吗?
List<Integer> element = new ArrayList<>();
element.add(5);
是的,02是正确的,因为有自动装箱
。
自动装箱是Java编译器在原始类型和其对应的包装类之间进行的自动转换。
然后5通过自动装箱转换为Integer值。
int
在 C# 的库函数中是预定义的,但在 Java 中我们可以创建 Integer
对象。
int
是原始类型(不能有null值),而Integer是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是一种原始数据类型,而Integer是一个对象。 使用Integer创建对象将使您可以访问Integer类中可用的所有方法。 但是,如果使用int创建原始数据类型,则无法使用这些内置方法,您必须自己定义它们。 但是,如果您不想使用其他方法并希望使程序更加内存高效,则可以使用原始数据类型,因为创建对象会增加内存消耗。
int 是一种原始数据类型。 Integer 是一个包装类。它可以将 int 数据存储为对象。
Integer a = new Integer()
。因此,在泛型中,不使用Integer
而是使用int
,所以没有这样的区别。