java中Integer的特殊之处

首先来看一个例子:

<!-- lang: java -->
            Integer a1 = 10;
    Integer a2 = 10;
    
    System.out.println(a1 == a2);
    Integer b1 = new Integer(100);
    Integer b2 = new Integer(100);
    System.out.println(b1 == b2);
    
    Integer c1 = 1000;
    Integer c2 = 1000;
    System.out.println(c1 == c2);

输出结果:true false false 原因:在使用自动装箱创建一个Integer对象时,如果值在-128-127之间 时,会将值放入缓冲池,如果下次在创建这个值得 Integer对象,测直接 使用这个值得引用,如果不在此区间内,就创建新的对象,这种方法称为 享元模式。比较a1,a2,a1,a2属于同一个对象,b1,b2创建的不同的对象 c1,c2,创建的不同的对象。

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0