首页 > 编程语言 > 详细

java Integer判等的大坑

时间:2018-01-24 15:10:26      阅读:213      评论:0      收藏:0      [点我收藏+]

在-128 至 127 范围内的赋值,Integer 对象是在IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行 判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑, 推荐使用 equals 方法进行判断。 

public class Program {
    public static void main(String[] args) {
        Integer a1 = 1;
        Integer b1 = 1;
        System.out.println(a1 == b1);        // true
        System.out.println(a1.equals(b1));    // true
        System.out.println(a1 == 1);        // true

        Integer a2 = 128;
        Integer b2 = 128;
        System.out.println(a2 == b2);        // false
        System.out.println(a2.equals(b2));    // true
        System.out.println(a2 == 128);        // true
    }
}

 

java Integer判等的大坑

原文:https://www.cnblogs.com/mousewheel/p/8341311.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!