我想创建一个实现通用接口(interface) Comparable 并覆盖方法 equals、hashCode 和 toString 的 Employee 类...我该怎么做?
这样可以吗
interface MinMax<T extends Comparable<T>> {
T equals();
T hashCode();
T toString();
}
和
class Employee<T extends Comparable<T>> implements MinMax<T> {
public T equals(){
}
public T hashCode(){
}
public T toString(){
}
}
最佳答案
这个问题有两个部分。
第 1 部分:覆盖 equals、hashCode 和 toString。
只需使用新实现在新类中重新定义这些方法即可。
class Employee {
//fields and other methods
public boolean equals(Object other) {
//new implementation here
}
public int hashCode() {
//make sure two equal objects produce the same hashCode
}
public String toString() {
//return whatever you want here
}
}
第 2 部分:实现 Comparable 接口(interface)。
我假设您希望与其他员工进行比较。声明它实现了Comparable,实现了接口(interface)描述的compareTo方法。
public Employee implements Comparable<Employee> {
//fields and methods
public int compareTo(Employee e) {
//new implementation. Should probably be consistent with equals.
}
}
关于Java 通用接口(interface)扩展了 Comparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379343/