我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
当前回答
使用包装类的原因有很多:
我们得到了额外的行为(例如,我们可以使用方法) 我们可以存储空值,而在原语中则不能 集合支持存储对象,而不支持存储原语。
其他回答
int变量保存一个32位有符号整数值。Integer(大写I)保存对(类)类型Integer或null对象的引用。
Java自动在两者之间进行类型转换;当Integer对象作为int操作符的参数出现,或者被赋值给int变量,或者一个int值被赋值给Integer变量时,从Integer到int。这种类型转换称为装箱/解装箱。
如果一个引用null的Integer变量被显式或隐式地解盒,则抛出NullPointerException异常。
在c#中,int只是System的别名。Int32,系统的字符串。字符串,double for System。双等等……
我个人更喜欢int, string, double等,因为他们不需要使用系统;这是个愚蠢的理由,我知道……
(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 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.
我将对上面给出的优秀答案进行补充,并讨论装箱和拆箱,以及如何将其应用于Java(尽管c#也有)。我将只使用Java术语,因为我对它更熟悉。
正如答案所提到的,int只是一个数字(称为未装箱类型),而Integer是一个对象(包含数字,因此是装箱类型)。在Java术语中,这意味着(除了不能在int上调用方法之外),您不能在集合(List, Map等)中存储int或其他非对象类型。为了存储它们,必须首先将它们装入相应的盒装类型中。
Java 5以后有了所谓的自动装箱和自动拆箱,允许装箱/拆箱在幕后完成。比较和对比:Java 5版本:
Deque<Integer> queue;
void add(int n) {
queue.add(n);
}
int remove() {
return queue.remove();
}
Java 1.4或更早版本(也没有泛型):
Deque queue;
void add(int n) {
queue.add(Integer.valueOf(n));
}
int remove() {
return ((Integer) queue.remove()).intValue();
}
必须注意的是,尽管Java 5版本很简洁,但两个版本生成的字节码是相同的。因此,尽管自动装箱和自动拆箱非常方便,因为您编写的代码更少,但这些操作确实发生在幕后,具有相同的运行时成本,因此您仍然必须知道它们的存在。
希望这能有所帮助!