我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
当前回答
01. 整数可以为空。但是int不能为null。
Integer value1 = null; //OK
int value2 = null //Error
02. 只能将包装器类类型值传递给任何集合类。
(包装类-布尔,字符,字节,短,整数,长,浮动,双)
List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer valueInteger = new Integer(value);
element.add(valueInteger);
但通常我们在集合类中添加原始值?02点正确吗?
List<Integer> element = new ArrayList<>();
element.add(5);
是的02是正确的,因为自动装箱。
自动装箱是java编译器进行的自动转换 原始类型与其对应的包装器类之间。
然后5转换为整型值自动装箱。
其他回答
我将对上面给出的优秀答案进行补充,并讨论装箱和拆箱,以及如何将其应用于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版本很简洁,但两个版本生成的字节码是相同的。因此,尽管自动装箱和自动拆箱非常方便,因为您编写的代码更少,但这些操作确实发生在幕后,具有相同的运行时成本,因此您仍然必须知道它们的存在。
希望这能有所帮助!
“int”是原始数据类型,是Java包装类中的“Integer”。“Integer”可以用作需要对象的方法的参数,而“int”可以用作需要整数值的方法的参数,可用于算术表达式。
Java已经回答了这个问题,下面是c#的答案:
“Integer”在c#中不是一个有效的类型名称,“int”只是System.Int32的别名。此外,与Java(或c++)不同,c#中没有任何特殊的基本类型,c#中类型的每个实例(包括int)都是一个对象。下面是一些演示代码:
void DoStuff()
{
System.Console.WriteLine( SomeMethod((int)5) );
System.Console.WriteLine( GetTypeName<int>() );
}
string SomeMethod(object someParameter)
{
return string.Format("Some text {0}", someParameter.ToString());
}
string GetTypeName<T>()
{
return (typeof (T)).FullName;
}
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中,int是一个基本数据类型,而Integer是一个Helper类,它用于将一种数据类型转换为另一种数据类型。
例如:
double doubleValue = 156.5d;
Double doubleObject = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();
基本数据类型存储最快的可用内存,而Helper类是复杂的,存储在heep内存中。
参考“David Gassner”Java基本训练。