我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
当前回答
Int是基本数据类型。 Integer是一个包装器类。它可以将int型数据存储为对象。
其他回答
在Java等平台中,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 1.5和自动装箱,在比较Integer对象时有一个重要的“怪癖”。
在Java中,值为-128到127的Integer对象是不可变的(也就是说,对于一个特定的整数值,比如23,通过程序实例化的所有值为23的Integer对象都指向完全相同的对象)。
例如,返回true:
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2); // true
而这返回false:
Integer i1 = new Integer(128);
Integer i2 = new Integer(128);
System.out.println(i1 == i2); // false
==通过引用进行比较(变量是否指向同一个对象)。
根据所使用的JVM的不同,这个结果可能不同,也可能没有不同。Java 1.5的规范自动装箱要求整数(-128到127)始终装入同一个包装器对象。
一个解决方案吗?当比较Integer对象时,应该总是使用Integer.equals()方法。
System.out.println(i1.equals(i2)); // true
更多信息请访问bexhuff.com
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.