java-基础入门-自动装箱与自动拆箱留给我们的坑

其实,java在自动装箱和自动拆箱的过程里面,留了不少的坑给我们,我们下面将以integer这个类为基础讨论一下

其实这里面主要涉及的是两点

1.当使用Integer x=1,这样的方式来赋值的时候,其实,编译器当那个1是String,然后需要通过valueof的方法转换过来,但是在转换的过程中,他为了优化速度,使用了我们所不知道的缓存,因为在这里会出现一些坑

2.Integer类里面重写了equals方法,里面不但对比对象,而且还对比里面的值


下面先上代码:(请仔细观看注释,里面已经提供了上面所述两个方法的源码)

package com.ray.object;

/**
 * 自动装箱与自动拆箱的坑
 * 
 * @author ray
 * @since 2015-05-04
 * @version 1.0
 * 
 */
public class Test {

	public static void main(String[] args) {
		// 其实下面这几句后面的赋值1,1,1000,1000,都被当做是string,
		// 然后通过Integer.valueOf()这个方法转换过来,
		// 我们下面来看看Integer.valueOf()这个方法的源码
		// public static Integer valueOf(int i) {
		// if(i >= -128 && i <= IntegerCache.high)
		// return IntegerCache.cache[i + 128];
		// else
		// return new Integer(i);
		// }
		// 在源码里面其实是缓存了一部分数据,是-128-127
		// 因此,在a==b是返回true
		// c==d是返回false
		Integer a = 1;
		Integer b = 1;
		Integer c = 1000;
		Integer d = 1000;
		System.out.println("a == b ---- " + (a == b));// true
		System.out.println("c == d ---- " + (c == d));// false
		// 这下面是构造4个integer的对象出来
		Integer a_1 = new Integer(1);
		Integer b_1 = new Integer(1);
		Integer c_1 = new Integer(1000);
		Integer d_1 = new Integer(1000);
		// 下面两句是通过==对比对象,当然是false了
		System.out.println("a_1 == b_1 ---- " + (a_1 == b_1));// false
		System.out.println("c_1 == d_1 ---- " + (c_1 == d_1));// false
		// 下面两句是通过equals对比对象,integer类里面重写了equals方法
		// 看看重写后equals方法的代码
		// public boolean equals(Object obj) {
		// if (obj instanceof Integer) {
		// return value == ((Integer)obj).intValue();
		// }
		// return false;
		// }
		// 我们可以看到出来对比对象之外,还对比本身的值,所以返回true
		System.out.println("a_1.equals(b_1) ---- " + a_1.equals(b_1));// true
		System.out.println("c_1.equals(d_1) ---- " + c_1.equals(d_1));// true
	}
}



输出:

a == b ---- true
c == d ---- false
a_1 == b_1 ---- false
c_1 == d_1 ---- false
a_1.equals(b_1) ---- true
c_1.equals(d_1) ---- true




版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/raylee2007/p/4774572.html