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

那么,有什么不同呢?


当前回答

int变量保存一个32位有符号整数值。Integer(大写I)保存对(类)类型Integer或null对象的引用。

Java自动在两者之间进行类型转换;当Integer对象作为int操作符的参数出现,或者被赋值给int变量,或者一个int值被赋值给Integer变量时,从Integer到int。这种类型转换称为装箱/解装箱。

如果一个引用null的Integer变量被显式或隐式地解盒,则抛出NullPointerException异常。

其他回答

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

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是int的包装对象。

一个使用Integer和int的例子,当你想比较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”是原始数据类型,是Java包装类中的“Integer”。“Integer”可以用作需要对象的方法的参数,而“int”可以用作需要整数值的方法的参数,可用于算术表达式。

在Java和c#中,int和Integer是用来表示不同事物的两个不同术语。它是可以赋值给可以精确存储的变量的基本数据类型之一。每次只声明其类型的一个值。

例如:

int number = 7;

其中int是赋给值为7的变量number的数据类型。所以int型只是一个原语,不是一个对象。

而Integer是具有静态方法的基元数据类型的包装类。That可以用作需要对象的方法的参数,其中as int可以用作需要整数值的方法的参数,可用于算术表达式。

例如:

Integer number = new Integer(5);