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

那么,有什么不同呢?


当前回答

还有一件事我在之前的回答中没有看到: 在Java中,原始包装类如Integer, Double, Float, Boolean…和String应该是不变的,所以当你传递这些类的实例时,被调用的方法不能以任何方式改变你的数据,在opositión中,大多数其他类的内部数据可以被它的公共方法改变。所以这个类只有getter方法,没有setter方法,除了构造函数。

在java程序中,字符串字面量存储在堆内存的单独部分中,只有一个字面量的实例,以节省重用这些实例的内存

其他回答

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.

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

在Java中,int类型是基本数据类型,而Integer类型是对象。

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

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

嗯,在Java中,int是一个原语,而Integer是一个对象。意思是,如果你创建了一个新的Integer:

Integer i = new Integer(6);

你可以在i上调用一些方法:

String s = i.toString();//sets s the string representation of i

而对于int类型:

int i = 6;

您不能在它上调用任何方法,因为它只是一个原语。所以:

String s = i.toString();//will not work!!!

会产生一个错误,因为int不是一个对象。

int是Java中为数不多的基本类型之一(还有char和其他一些基本类型)。我不是100%确定,但我认为Integer对象或多或少只是有一个int属性和一大堆方法与该属性进行交互(例如toString()方法)。因此Integer是处理int的一种奇特方式(就像String是处理一组字符的奇特方式一样)。

我知道Java不是C语言,但由于我从未用C语言编程,这是我能找到的最接近答案的方法。

整数对象javadoc

Integer Ojbect与int原语比较