Integer关于equals与==的比较(自动拆装箱技术和常量池技术)

      首先介绍下 equals方法遵循的规则:自反性,一致性,传递性,对称性,与null相比,返回false;

      1.JAVA当中所有的类都是继承于Object这个基类的,在Object中的基类中定义了一个equals的方法,在没有覆写equals方法的情况下,他们之间的比较还是基于他们在内存中的存放位置的地址值的,因为Object的equals方法也是用双等号(==)进行比较的,所以比较后的结果跟双等号(==)的结果相同。Object中的equals方法源代码:

public boolean equals(Object obj) {
        return (this == obj);
    }

      2.在一些类库当中这个方法被覆盖掉了,如String,Integer,Date在这些类当中equals有其自身的实现,而不再是比较类在堆内存中的存放地址了。如:Integer 中的equals源代码:

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
      在定义Integer a=5;此语句中,相当于一个自动装箱的过程,即Integer a=Integer.valueof(5);我们再来看一下valueof方法的源代码:
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
      当包装类对应的值在-128到127的范围内时,即存入常量池中,但超过这个范围时,便会在堆中创建一个新的对象;因此用==比较两个Integer对象时,在-128到127则返回true,不在这个范围则返回false;
      当一个基本类型与包装类型进行比较时,会自动拆箱,即调用intvalue方法:
public int intValue()  
{  
  return value;  
}

public class Test{
    public static void main(String[] args) {
       Integer a = new Integer(200);
        Integer b = new Integer(200);
        Integer c = 200;
        Integer e = 200;
       int d = 200;


         System.out.println("两个new出来的对象    ==判断"+(a==b));
        System.out.println("两个new出来的对象    equal判断"+a.equals(b));
        System.out.println("new出的对象和用int赋值的Integer   ==判断"+(a==c));
        System.out.println("new出的对象和用int赋值的Integer   equal判断"+(a.equals(c)));
       System.out.println("两个用int赋值的Integer    ==判断"+(c==e));
       System.out.println("两个用int赋值的Integer    equal判断"+(c.equals(e)));
       System.out.println("基本类型和new出的对象   ==判断"+(d==a));
       System.out.println("基本类型和new出的对象   equal判断"+(a.equals(d)));
       System.out.println("基本类型和自动装箱的对象   ==判断"+(d==c));
        System.out.println("基本类型和自动装箱的对象   equal判断"+(c.equals(d)));
    }
  }
运行结果:
两个new出来的对象    ==判断false
两个new出来的对象    equal判断true
new出的对象和用int赋值的Integer   ==判断false
new出的对象和用int赋值的Integer   equal判断true
两个用int赋值的Integer    ==判断false
两个用int赋值的Integer    equal判断true
基本类型和new出的对象   ==判断true
基本类型和new出的对象   equal判断true
基本类型和自动装箱的对象   ==判断true
基本类型和自动装箱的对象   equal判断true

注:java中基本类型的包装类的大部分都实现了常量池技术,这些类是Byte,Short,Integer,Long,Character,Boolean,另外两种浮点数类型的包装类则没有实现。另外Byte,Short,Integer,Long,Character这5种整型的包装类也只是在对应值小于等于127时才可使用对象池,也即对象不负责创建和管理大于127的这些类的对象。
       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值