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

那么,有什么不同呢?


当前回答

Int用于声明原始变量

e.g. int i=10;

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

Integer a = new Integer();

其他回答

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

例如:

int number = 7;

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

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

例如:

Integer number = new Integer(5);

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

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

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

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

int x;
Integer y; 

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

Integer.toString(x);

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

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