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

那么,有什么不同呢?


当前回答

Java:

Int, double, long, byte, float, double, short, boolean, char - primitives。用于保存基本数据类型 由语言支持。类的基本类型不是 对象层次结构,并且它们不继承object。不能通过对方法的引用来传递。

Double、Float、Long、Integer、Short、Byte、Character和Boolean都是类型包装器,打包在java.lang中。所有数字类型包装器都定义了构造函数,允许从给定值或该值的字符串表示形式构造对象。 即使是最简单的计算,使用对象也会增加开销。

从JDK 5开始,Java包含了两个非常有用的特性:自动装箱和自动装箱。自动装箱/拆箱极大地简化和简化了必须将基本类型转换为对象的代码,反之亦然。

构造函数的例子:

Integer(int num)
Integer(String str) throws NumberFormatException
Double(double num)
Double(String str) throws NumberFormatException

装箱/拆箱的例子:

class ManualBoxing {
        public static void main(String args[]) {
        Integer objInt = new Integer(20);  // Manually box the value 20.
        int i = objInt.intValue();  // Manually unbox the value 20
        System.out.println(i + " " + iOb); // displays 20 20
    }
}

autoboxing/autounboxing的例子:

class AutoBoxing {
    public static void main(String args[]) {
        Integer objInt = 40; // autobox an int
        int i = objInt ; // auto-unbox
        System.out.println(i + " " + iOb); // displays 40 40
    }
}

附注:赫伯特·斯希尔特的书被作为参考。

其他回答

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

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


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

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

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用于声明原始变量

e.g. int i=10;

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

Integer a = new Integer();

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转换为整型值自动装箱。

嗯,在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原语比较