maojianyun
2019-07-11 10:24:49
java实体类中equals和hashCode方法的重写
使用jdk8新特性去重需要重写equals和hashCode方法
public class StudentEntity{ private int id; private String name; private int grade; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof StudentEntity) { StudentEntity entity = (StudentEntity) obj; return entity.getId() == this.getId() && entity.getName().equals(this.getName()) && entity.getGrade() == this.getGrade(); } return false; } @Override public int hashCode() { int result; long temp; result = id; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + grade; return result; } }
评论
最近浏览
userfzh LV1
2021年8月12日
abcmin
2021年5月16日
暂无贡献等级
豆子小兔子 LV9
2020年9月8日
wjk999999
2020年3月12日
暂无贡献等级
maojianyun LV30
2020年1月10日