gpt4 book ai didi

java - equals()、hashcode() 和compare() 方法内部到底发生了什么?

转载 作者:行者123 更新时间:2023-12-01 18:06:15 25 4
gpt4 key购买 nike

我对 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;
}

}

[编辑1]疑问1:每个比较的真正含义是什么?

现在我已经实现了比较器接口(interface)及其方法。

  class EmpNameComparator implements Comparator<Employee> {
@Override
public int compare(Employee a, Employee b) {
return a.name.compareToIgnoreCase(b.name);
}
}

[编辑2]疑问2:它是要比较List<>中的两个辅助对象还是发生其他事情,它内部做了什么?

最佳答案

this == obj 检查当前对象是否与另一个对象相同

如果它们是同一个Object,当然它们也是“相等”的。

compareToIgnoreCase比较两个 String 对象,忽略大小写差异:

Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character.

因此,当您使用自定义比较器对 Employee 列表进行排序时:

Collections.sort(employeeList, new EmpNameComparator());

两名同名员工(忽略大小写),将被视为同一员工进行排序操作。

请注意,您无法判断 John 是否会出现在 joHn 之前,或者相反。

关于java - equals()、hashcode() 和compare() 方法内部到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36216924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com