我在阅读《关于软件的更多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)是你可以为变量设置的基本类型之一(就像char, float,…)
但是Integer是一个包装类,你可以使用它对int变量执行一些函数(例如将它转换为字符串或反之亦然,…),但请注意包装类中的方法是静态的,所以你可以随时使用它们,而无需创建Integer类的实例。 回顾一下:
int x;
Integer y;
x和y都是int类型的变量,但是y是由一个Integer类包装的,并且有几个你使用的方法,但如果你需要调用Integer包装类的一些函数,你可以简单地做到这一点。
Integer.toString(x);
但请注意,x和y都是正确的,但如果您想将它们仅作为基本类型使用,请使用简单形式(用于定义x)。
关于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.
在Java等平台中,int是基本类型,而Integer是一个包含整数字段的对象。重要的区别是,原语总是通过值传递,并且通过定义是不可变的。
任何涉及基本变量的操作总是返回一个新值。另一方面,对象是通过引用传递的。有人可能会说指向对象的点(又名引用)也通过值传递,但内容不是。