关于使用ObjectUtils.equals方法进行参数比较出现的问题

RT,正常在写代码,然后发现出了bug,采用二分排除法才找到原因:ObjectUtils.equals(a,b)这个判断出现问题了。

大概实例代码如下:

1.

        Map<String, Double> measureFlow = new HashMap<>();
        int measure = 4;
        measureFlow.put("measure",(double)measure);

2.

if (ObjectUtils.equals(measureFlow.get("measure"),4)) {

    //业务代码

}

就是一个方法返回Map<String,Double>类型值,然后拿到map中的measure参数和数字4比较。本来应该是true的,结果却是false。

然后源码是这样的:

public static boolean equals(Object object1, Object object2) {
        if (object1 == object2) {
            return true;
        } else {
            return object1 != null && object2 != null ? object1.equals(object2) : false;
        }
    }

于是我进行测试:

System.out.println(measureFlow.get("measure")==4);

返回是true,这个和源码里的object1 == object2 不是一样一样的吗?为什么源码里面就是false,我自己这样写就是true?

于是我断点看了一下,终于发现了问题

 原来,在进行比较的时候,基础类型的参数需要进行装箱,int类型的4被封装成了Integer,所以进行比较的两个对象一个是Double类型的,一个是Integer类型的,所以就是false了。

@RequestMapping("/systemChange") public String systemChange(String id) { Student student = studentService.getById(id); LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<>(); studentLambdaQueryWrapper.eq(Student::getSex,student.getSex()); //班级的学生 if (!ObjectUtils.isEmpty(student.getGrade())){ studentLambdaQueryWrapper.eq(Student::getGrade,student.getGrade()); } //并且存在宿舍的 studentLambdaQueryWrapper.isNotNull(Student::getDormitoryId); List<Student> studentList = studentService.list(studentLambdaQueryWrapper); //查出自己的文件答案 LambdaQueryWrapper<TopicResult> topicResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); topicResultLambdaQueryWrapper.eq(TopicResult::getStuNum, student.getStudentNumber()) .and(qw -> qw.eq(TopicResult::getTopicId, 1).or().eq(TopicResult::getTopicId, 2)); List<TopicResult> topicResults = topicResultService.list(topicResultLambdaQueryWrapper); for (Student student1 : studentList) { LambdaQueryWrapper<TopicResult> topicResultLambdaQueryWrapper1 = new LambdaQueryWrapper<>(); topicResultLambdaQueryWrapper1.eq(TopicResult::getStuNum, student1.getStudentNumber()) .and(qw -> qw.eq(TopicResult::getTopicId, 1).or().eq(TopicResult::getTopicId, 2)); List<TopicResult> results = topicResultService.list(topicResultLambdaQueryWrapper1); if (topicResults.get(0).getOptionId().equals(results.get(0).getOptionId()) || topicResults.get(1).getOptionId().equals(results.get(1).getOptionId()) ){ Dormitory dormitory = dormitoryService.getById(student1.getDormitoryId()); if (dormitory.getNum()<dormitory.getTotal()){ student.setDormitoryId(dormitory.getId()); studentService.updateById(student); dormitory.setNum(dormitory.getNum()+1); dormitoryService.updateById(dormitory); return "redirect:list"; } } }请详细解释每一行代码
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值