包装类中难点问题

235 阅读2分钟

本篇文章是作为小白的学习笔记来写,用于记录学习过程中的一些不易掌握的问题。 先贴一段代码

public class WrapTest {
    public static void main(String[] args) {
        Integer one=new Integer(100);
        Integer two=new Integer(100);
        System.out.println(one==two);
        System.out.println(one==100);
        Integer three=100;
        Integer four=100;
        System.out.println(three==100);
        System.out.println(three==four);
        Integer five=200;
        Integer six=200;
        System.out.println(five==six);
        Double d1=100.0;
        Double d2=100.0;
        System.out.println(d1==d2);
    }
}


输出的结果为:

false
true
true
true
false
false

由于理不清引用相等,值相等的各种区分。希望在贴代码,解释代码的过程中,日积月累,记忆,理解,掌握这些内容。
  1. System.out.println(one==two);java当中等号两边放的如果是对象名,则比的是对象在内存当中的引用,而不仅仅是值,通过new关键字的实例操作,在内存中开辟新的对象空间,故结果为false。
  2. Integer three=100;这一句实际是自动装箱操作,System.out.println(three==100);而这一句实际是自动拆箱操作,此时等号两端比较数值。
  3. java在执行自动拆装箱操作时,其核心便是valueOf方法,Integer four=100;→Integer four=Integer.valueOf(100);在执行valueOf的操作时,提供了类似于常量数的缓存区(对象池),如果传入参数(-128,127),会直接从缓存中查找是否有该对象,如果有,则直接产生,没有则实例化一个该对象因此当three和four在执行自动装箱操作时,他们指向的时缓存区内的同一块空间,因此System.out.println(three==four);的输出结果为true。

    而five和six由于参数在范围之外,故通过new关键字构造新的内存空间,所以System.out.println(five==six);的结果为false。

  4. 八种数据类型对应的包装类,除了Double和Float,其它都可以应用对象常量池的概念.
        Double d1=100.0;
        Double d2=100.0;
        System.out.println(d1==d2);
    

    因此该结果为false。