主要通过打印验证包装类与基本数据类型之间的比较,讲解比较少,代码以int 和 Integer为例,看代码吧
拆装箱: jdk1.4以后,包装类提供了自动拆箱自动装箱的过程。 即java会在 int--Integer / double--Double等包装类与对应的基本数据类型之间进行自动转换,无需代码(例如:Integer.valueOf(int)等)转换。
import java.io.*;
class test
{
public static void main (String[] args) throws java.lang.Exception
{
//--------跨类型 int 与integer 拆装箱 ------------------------
int i = 128;
Integer j = new Integer(128);
Integer k = 128;
System.out.println(i == j); //true 拆箱
System.out.println(i == k); //true 拆箱
System.out.println(j.equals(i)); //true 装箱
System.out.println(k.equals(i)); //true 装箱
//-------同类型(Integer)-------------------------------------
// "="给对象赋值
// 赋值范围-128~127,使用常量池,==比较为true
Integer i1 = 1;
Integer j1 = 1;
System.out.println(i1 == j1); //true
System.out.println(i1.equals(j1)); //true
// "="给对象赋值
//超范围(-128以下 127以上),建对象,对象间==比较为False
Integer i11 = 128;
Integer j11 = 128;
System.out.println("1-2");
System.out.println(i11 == j11); //fale
System.out.println(i11.equals(j11)); //true
//"new" 建对象赋值,不考虑范围,对象间==比较都为False
Integer i2 = new Integer(1);
Integer j2 = new Integer(1);
System.out.println(i2 == j2); //false
System.out.println(j2.equals(i2)); //true
// = & new (混合),对象间==比较都为False
Integer i3 = 1;
Integer j3 = new Integer(1);
System.out.println("\n3");
System.out.println(i3 == j3); //false
System.out.println(j3.equals(i3)); //true
}
}
输出结果:
true
true
true
true
true
true
false
true
false
true
false
true