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

其他回答

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

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

在Java等平台中,int是基本类型,而Integer是一个包含整数字段的对象。重要的区别是,原语总是通过值传递,并且通过定义是不可变的。

任何涉及基本变量的操作总是返回一个新值。另一方面,对象是通过引用传递的。有人可能会说指向对象的点(又名引用)也通过值传递,但内容不是。

Int用于声明原始变量

e.g. int i=10;

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

Integer a = new Integer();

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;
}

在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

现在你看到区别了吗?