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

来源:互联网 发布:c语言vc6.0软件下载 编辑:程序博客网 时间:2024/06/01 09:40

      首先介绍下 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判断truenew出的对象和用int赋值的Integer   ==判断falsenew出的对象和用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