我在阅读《关于软件的更多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#的答案:

“Integer”在c#中不是一个有效的类型名称,“int”只是System.Int32的别名。此外,与Java(或c++)不同,c#中没有任何特殊的基本类型,c#中类型的每个实例(包括int)都是一个对象。下面是一些演示代码:

void DoStuff()
{
    System.Console.WriteLine( SomeMethod((int)5) );
    System.Console.WriteLine( GetTypeName<int>() );
}

string SomeMethod(object someParameter)
{
    return string.Format("Some text {0}", someParameter.ToString());
}

string GetTypeName<T>()
{
    return (typeof (T)).FullName;
}

int在库函数c#中是预定义的,但在java中我们可以创建Integer对象

在Java中,JVM有两种基本类型。1)基本类型和2)引用类型。int是基本类型,Integer是类类型(一种引用类型)。

基元值不与其他基元值共享状态。类型为基本类型的变量总是保存该类型的基本值。

int aNumber = 4;
int anotherNum = aNumber;
aNumber += 6;
System.out.println(anotherNum); // Prints 4

对象是动态创建的类实例或数组。引用值(通常只是引用)是指向这些对象的指针和一个特殊的空引用,它不引用任何对象。同一个对象可能有多个引用。

Integer aNumber = Integer.valueOf(4);
Integer anotherNumber = aNumber; // anotherNumber references the 
                                 // same object as aNumber

在Java中,所有东西都是通过值传递的。对于对象,传递的值是对象的引用。因此,java中int和Integer的另一个区别是它们在方法调用中传递的方式。例如在

public int add(int a, int b) {
    return a + b;
}
final int two = 2;
int sum = add(1, two);

变量2作为原始整数类型2传递。而在

public int add(Integer a, Integer b) {
    return a.intValue() + b.intValue();
}
final Integer two = Integer.valueOf(2);
int sum = add(Integer.valueOf(1), two);

变量two作为一个引用传递给一个保存整数值2的对象。


@WolfmanDragon: 通过引用传递将像这样工作:

public void increment(int x) {
  x = x + 1;
}
int a = 1;
increment(a);
// a is now 2

当increment函数被调用时,它传递一个指向变量a的引用(指针),并且increment函数直接修改变量a。

对于对象类型,它的工作方式如下:

public void increment(Integer x) {
  x = Integer.valueOf(x.intValue() + 1);
}
Integer a = Integer.valueOf(1);
increment(a);
// a is now 2

现在你看到区别了吗?

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

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

int x;
Integer y; 

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

Integer.toString(x);

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