> 文章列表 > 案例09-数据类型不一致导致equals判断为false

案例09-数据类型不一致导致equals判断为false

案例09-数据类型不一致导致equals判断为false

一:背景介绍

        在判断课程id和班级id的时候如果一致就像课程信息进行更新,如果不一致就插入一条新的数据。其实两个变量的值是一致的但是类型是不一致的。这就导致数据库中已经有一条这样的数据了,在判断的时候结果为false,就有插入了一条相同课程班级的数据。数据发生了混乱。

二:思路&方案

        分析equals方法判断两个对象的什么内容,是对象的值还是对象的地址以及基本数据类型的对象是否重写了equals方法。

三:过程

1.通过demo来验证equals方法

/*** @BelongsProject: demo* @BelongsPackage: com.wzl.EqualsByType* @Author: Wuzilong* @Description: equals判断* @CreateTime: 2023-03-03 14:13* @Version: 1.0*/public class DifferentType {public static void main(String[] args) {Long  firstVariable =555L;String secondVariable="555";String thirdVariable="555";System.out.println("类型不一致"+firstVariable.equals(secondVariable));System.out.println("类型一致"+secondVariable.equals(thirdVariable));}}

 

 从执行的结果来看,类型的不一致会导致调用equals方法为false。

2.看一下equals方法的源码

        equals是object类的方法,从object类中看equals方式是比较的对象的地址。也可以从方法的

注释上分析出比较的是两个对象的地址。

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Params:
obj – the reference object with which to compare.
Returns:
true if this object is the same as the obj argument; false otherwise.public boolean equals(Object obj) {return (this == obj);}

        当我们从例子中的点击进去看equals方法的源码的时候,发现基本数据类型包装类对equals方法进行了重写。

public boolean equals(Object obj) {if (obj instanceof Long) {return value == ((Long)obj).longValue();}return false;}

        重写之后我们发现在基本数据类型包装类调用的equals方法中会判断传入的对象是不是Long包装类的实例,如果不是就直接返回false。从上面的例子来看String类型的对象不是Long包装类的实例所以直接返回了false。

四:总结

        1.equals方法如果没有进行重写操作的话去比较两个对象的地址

        2.如果对equals方法进行重写,按照重写的逻辑进行。比如判断值或者即判断值有判断地址。

五:升华

        我们平时在调用String、Integer等包装类型时的equals方法时是比较的内容是否一致而不是地址一是否致,如果是地址一致,那所有的String类型比较都是相等的,所以包装类类型都重写了equals方法。我们可以根据业务场景的不同来选择是否重写equals方法。