包装类与基本类型比较大小
/*
Integer 两种声明方式(创建对象):new 和 直接赋值
先去缓存区找一下有没有对应的,
有,此时为常量对象
🔸对于new: 变量存储的地址,实际对象为常量对象
🔸对于直接赋值: 变量存储的是常量值
没有,重新"new"对象,在堆中开辟空间
🔸对于new: 存储的地址,新开辟内存
🔸对于直接赋值: 存储的也是地址,新开辟内存
(只要出现new,一定在堆中开辟了空间,存储的即地址)
*/
/*Integer的直接赋值 ,缓存内是常量值,超出缓存是地址嘛
可以理解为超出缓存的话,直接赋值与new等价
缓存内的话,直接赋值是一个常量值(类似String字符串直接赋值)
包装类与基本类型一定相等,无论在不在缓存区,包装类无论new还是直接赋值
包装类与包装类,除了两个直接赋值比较相等(本质两个常量值比较),其余结果均为false
*/
public class MyInt{
public static void main(String[] args){
//缓存区内-128~127(常量对象)
Integer i1=new Integer(123);
Integer i2=new Integer(123);
Integer i7=123;
Integer i77=123;
int i3=123;
//超过缓存,实例对象
int i4=345;
Integer i5=345;
Integer i55=345;
Integer i6=new Integer(345);
Integer i8=new Integer(345);
//1、两对象之间比较:
//(1)Integer:两个new -->false false
System.out.println("new两个Integer\n\n(缓存区内):"+(i1==i2));//new对象声明在堆中,==比较地址是否相等
System.out.println("(超过缓存区):"+(i6==i8));
System.out.println("--------------------\n");
/*结论:new声明在堆中,比较的地址,无论缓存中有无,均不相等*/
//(2)Integer:new和直接赋值 -->false false
System.out.println("两个Integer(其中一个new一个直接赋值)\n\n(缓存内):"+(i2==i7));//
System.out.println("(超过缓存):"+(i5==i6));
System.out.println("--------------------\n");
//(3)Integer:两个直接赋值 -->true false
System.out.println("两个Integer(直接赋值)\n\n(缓存内):"+(i77==i7));//两个常量比较
System.out.println("(超过缓存):"+(i5==i55));
System.out.println("--------------------\n");
//2、包装类与基本类型比较: 自动装箱、拆箱,任意Integer与int比较都是true
//(1)Integer包装类[new对象]与int基本类型比较
System.out.println("Integer与int(new与int)\n\n(缓存区内):"+(i2==i3));//Integer包装类与int基本类型比较,会自动拆箱,比较值是否相等
System.out.println("(超过缓存区):"+(i4==i6));
System.out.println("--------------------\n");
//(2)Integer包装类[直接赋值]与int基本类型比较
System.out.println("Integer与int(直接赋值与int)\n\n(缓存区内):"+(i7==i3));//Integer包装类与int基本类型比较,会自动拆箱,比较值是否相等
System.out.println("(超过缓存区):"+(i4==i5));
System.out.println("--------------------\n");
运行结果: