1.概念
装箱就是 自动将基本数据类型转换为包装器类型;
拆箱就是 自动将包装器类型转换为基本数据类型;
2.装箱和拆箱是如何实现的
装箱过程是通过调用包装器的valueOf方法实现的,
而拆箱过程是通过调用包装器的 xxxValue方法实现的。(xxx代表对应的基本数据类型)。
public class Test1 {
public static void main(String[] args) {
Integer x = 100;
int ints = x.intValue();
int ints2 =100;
Integer y = Integer.valueOf(ints2);
// i >= -128 && i <= Integer.IntegerCache.high ? Integer.IntegerCache.cache[i + 128] : new Integer(i);
}
}
Integer x1 =10;
System.out.println(x1.equals(5+5));
if (obj instanceof Integer) {
return this.value == (Integer)obj;
(c.equals(a+b)会先触发自动拆箱过程,再触发自动装箱过程,也就是说a+b,会先各自调用intValue方法,得到了加法运算后的数值之后,便调用Integer.valueOf方法,再进行equals比较)
Integer x1 = 10;
Integer x2 = 10;
int x3 = 10;
System.out.println(((Object) x3 instanceof Integer));
System.out.println(x1==(x3));
Long x4 =13L;
System.out.println(x4 .equals(x1));//f
System.out.println(x4 == (7+6));//t
System.out.println(x4.equals((7+6)));//f
(总结"=="中如果有运算符则是比较的值,如果没有运算符则是比较是否指向的是同一个对象,对于"equals"有运算符则先进行自动拆箱,得到结果之后进行自动装箱,注意"equals"方法并不会进行类型的转换.两边类型相同,如都是integer,则进行值比较。两边类型不同(一个Integer,一个Long)直接返回false,)
ublic boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
网友评论