转载自:https://blog.csdn.net/qq_28051453/article/details/52701171
一、什么是hashCode()、equals()方法?
二、hashCode(),equals()两种方法是什么关系?
三、为什么在重写equals方法的时候要重写hashCode的方法?
四、怎么重写这两种方法?
public class SimpleDemo { // 部门 private String department; // 工号 private int id; public SimpleDemo(int id, String department) { super(); this.id = id; this.department = department; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getdepartment() { return department; } public void setdepartment(String department) { this.department = department; } @Override public int hashCode() { int hash = 1; hash = hash * 17 + id; hash = hash * 31 + department.hashCode(); return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj instanceof SimpleDemo) { SimpleDemo sd = (SimpleDemo) obj; return sd.department.equals(department) && sd.id == id; } return false; } ———————————————— 版权声明:本文为CSDN博主「南瓜灯cc」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_28051453/article/details/5270117