我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中int和Integer的区别。
那么,有什么不同呢?
我在阅读《关于软件的更多Joel》时,偶然看到Joel Spolsky说,有一种特殊类型的程序员知道Java/ c#(面向对象编程语言)中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版本) 简单来说,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中,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基本训练。
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;
}
在Java中,int类型是基本数据类型,而Integer类型是对象。
在c#中,int类型也是一种数据类型,与System.Int32相同。整数(就像任何其他值类型一样)可以被装箱(“包装”)到一个对象中。