java开发的一个意外——踩进了Long的自动拆装箱的坑

0x01

A同学在写考勤模块接口时候有一段代码片段是这样写的

//加班管理 列表
for(CiOverTime overTimePojo : overTimeList) {
    if(overTimePojo.getPersonid() == personDeptList.get(i).getRid()) {
        overTimePersonList.add(overTimePojo);
    }
}
printPojo.setOverTimeList(overTimePersonList);
//请假管理 列表
for(CiApplyLeave applyLeavePojo : applyLeaveList) {
    if(applyLeavePojo.getPersonid() == personDeptList.get(i).getRid()) {
        applyLeavePersonList.add(applyLeavePojo);
    }
}
printPojo.setApplyLeaveList(applyLeavePersonList);
//迟到早退 列表
for(CiWorkLate workLatePojo : workLateList) {
    if(workLatePojo.getPersonid() == personDeptList.get(i).getRid()) {
        workLatePersonList.add(workLatePojo);
    }
}
printPojo.setWorkLateList(workLatePersonList);
//旷工管理  列表
for(CiAbsent absentPojo : absentList) {
    if(absentPojo.getPersonid() == personDeptList.get(i).getRid()) {
        absentPersonList.add(absentPojo);
    }
}

测试部在黑盒测试该接口具体功能时,发现数据不全,只能显示一部分数据。 由于A同学已经跑路。 我就去调试下他的代码。发现

if(overTimePojo.getPersonid() == personDeptList.get(i).getRid()) 中 ==号前后 Long类型的值。

所以问题找到了 把== 改为 eq就行了。

0x02

问题结束了么?

还记得测试部说 部分数据可以显示么。。。。

那也就是说 Long类型对像 在==的作用下是可以出现 true的。。。

看代码

public static void main(String[] args) {
    Long testa = 125l;
    Long testb = 125l;
    
    Long testc = 1280l;
    Long testd = 1280l;
    
    System.out.println(testa==testb);
    System.out.println(testc==testd);
}

运行的结果为:

true

false

哦。这样,A同学挖了出了个大坑啊。。。

0x03

答案在valueOf方法中

以Long为例

首先下面的这两种写法作用是一样的,也就是Long的自动装箱

Long testa = Long.valueOf(125);
Long testa = 125l;

JDK源码(答案在这里)

 public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }


  private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }

你可能感兴趣的:(java开发的一个意外——踩进了Long的自动拆装箱的坑)