我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
当前回答
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变量保存一个32位有符号整数值。Integer(大写I)保存对(类)类型Integer或null对象的引用。
Java自动在两者之间进行类型转换;当Integer对象作为int操作符的参数出现,或者被赋值给int变量,或者一个int值被赋值给Integer变量时,从Integer到int。这种类型转换称为装箱/解装箱。
如果一个引用null的Integer变量被显式或隐式地解盒,则抛出NullPointerException异常。
Int用于声明原始变量
e.g. int i=10;
Integer用于创建类Integer的引用变量
Integer a = new Integer();
(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...}
关于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”是原始数据类型,是Java包装类中的“Integer”。“Integer”可以用作需要对象的方法的参数,而“int”可以用作需要整数值的方法的参数,可用于算术表达式。