- 我们都知道Java中有int,short,long,byte,float,double,char,和boolean等八个基本数据类型
- 为了面向对象操作的一致性,Java为每种基本数据类型都提供了相应的封装类型,并且提供相应的方法实现基本数据类型与封装类之间的相互转化
- 从JDK5.0版本开始引用了自动装箱和自动拆箱特性,主要的目的是方便封装类和基本类型之间的转化,该特性允许基本数据类型之间直接相互赋值.
下面看一段代码:
public class IntegerTest {
public static void main(String[] args) {
Integer in1 = new Integer(99);
Integer in2 = new Integer(99);
System.out.println(in1 == in2);
}
}
结果显而易见,一定是false,这个就不用多余的解释了,呵呵.....
再来看一段代码:
public class IntegerTest {
public static void main(String[] args) {
Integer in1 = new Integer(99);
Integer in2 = 99;
System.out.println(in1 == in2);
}
}
估计看到这里的时候有些人会开始鄙视我了,这么弱智的问题也摆出来.......
那好接下来开始进入正题:
示例1).
public class IntegerTest {
public static void main(String[] args) {
Integer in1 = 99;
Integer in2 = 99;
System.out.println(in1 == in2);
}
}
实例2).
public class IntegerTest {
public static void main(String[] args) {
Integer in1 = 199;
Integer in2 = 199;
System.out.println(in1 == in2);
}
}
- 看到这里估计你们已经可以肯定,楼主%*&$#,但你们可以给我一定可以的答案吗,true或者false???如果不能肯定的话运行测试一下吧,嘎嘎~~
|
不
|
|
理
|
|
解
|
|
的
|
|
孩
|
|
子
|
|
跟
|
|
我
|
|
下
|
|
来
|
|
- 相信到了这里的每个人心里都会想一样只是数字变了为神马结果却不同呢,别着急, 请看下面两个实例编译后的反编译代码:
反编译代码1).
import java.io.PrintStream;
public class IntegerTest
{
public IntegerTest()
{
}
public static void main(String args[])
{
Integer in1 = Integer.valueOf(99);
Integer in2 = Integer.valueOf(99);
System.out.println(in1 == in2);
}
}
反编译代码2).
import java.io.PrintStream;
public class IntegerTest
{
public IntegerTest()
{
}
public static void main(String args[])
{
Integer in1 = Integer.valueOf(199);
Integer in2 = Integer.valueOf(199);
System.out.println(in1 == in2);
}
}
看到这里想必我们都知道问题的所在了,valueOf方法,那好,我们看一下它的源码:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
- 看到这里我们都明白了,其实对于-128到127之间的数,Integer.valueOf(99)返回的是缓存中的对象,所以两次调用valueOf返回的是同一个对象,故结果是true.而Integer.valueOf(199)返回的则是重新实例化的对象,故结果是false.好了,自动装箱的问题有了一个初步的了解,那自动拆箱咧?动手实践一下吧!!!!!
- 反编译软件,见附件.......