本文主要是介绍呼呼哈哈自用--实体类重写equals和hashcode,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
开局奉上大神的文章链接
1.https://www.cnblogs.com/yuxiaole/p/9570850.html
2.https://www.cnblogs.com/myseries/p/10977868.html
package com.xxxx.domain.DO;/*** @author TXY*/
public class UserDO {private Long id;private String name;private Integer sex;public UserDO() {}public UserDO(Long id, String name, Integer sex) {this.id = id;this.name = name;this.sex = sex;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getSex() {return sex;}public void setSex(Integer sex) {this.sex = sex;}@Overridepublic boolean equals(Object anotherObj){//1.先判断是不是自己,提高运行效率//测试两个对象是否是同一个对象,是的话返回trueif(this == anotherObj){return true;}//测试检测的对象是否为空,是就返回falseif(anotherObj == null){return false;}//参数是否为正确的类型,提高代码健壮性//测试两个对象所属的类是否相同,否则返回falseif (anotherObj instanceof UserDO){//如果是--进行向下转型,父类无法调用子类的成员和方法UserDO anotherUserDO = (UserDO) anotherObj;//最后判断类的所有属性是否相等,其中String类型和Object类型可以用相应的equals()来判断//若姓名和性别一样,则对象相等if(this.getName().equals(anotherUserDO.getName()) &&this.getSex().equals(anotherUserDO.getSex())){return true;}}return false;}@Overridepublic int hashCode(){int result = 17;result = 31 * result + (name == null ? 0 : name.hashCode());result = 31 * result + (age == null ? 0 : age.hashCode());return result;}public static void main(String[] args) {UserDO user1 = new UserDO(1L, "xiaohua", 14);UserDO user2 = new UserDO(2L, "xiaohua", 14);System.out.println((user1.equals(user2))); //打印为true}
}
这篇关于呼呼哈哈自用--实体类重写equals和hashcode的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!