【发布时间】:2016-03-25 08:59:13
【问题描述】:
我真的对 hashcode() 和 equals() 方法的实现感到困惑。 这是代码的和平。
class Employee {
int id;
String name;
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
final int prime = 3;
int result = 1;
result = (prime * result) + id;
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
Employee other = (Employee) obj;
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
[edit 1]疑问1:每个比较的真正含义是什么?
现在我已经实现了比较器接口及其方法。
class EmpNameComparator implements Comparator<Employee> {
@Override
public int compare(Employee a, Employee b) {
return a.name.compareToIgnoreCase(b.name);
}
}
[edit 2] 疑问2:是要比较List中的两个adjusent对象还是发生其他事情,它在内部做了什么?
【问题讨论】:
-
“我真的很困惑”是一种心态,而不是一个问题。如果你在这里需要帮助,你必须提出一个精确的问题。如果您不能这样做,这不适合您。你最好咨询一本书和你的老师。
-
请将代码中使用列表的部分贴出来。
-
我没有在任何地方使用它,它只是为了理解目的。考虑到我在做 employeeList.sort();真正的 compare() 行为如何?
标签: java collections comparator