0

好吧,我还需要解决一个问题。我的哈希图代码添加/删除/修改/打印/排序(有点)。是排序问题。它按姓氏升序排列。如果两个员工的姓氏相同,则继续按名字升序。但问题是,如果这两个员工的名字也相同,那么它必须按 ID 号排序,而事实并非如此。

我的代码:如果两个员工的全名相同但身份证号不同,那么它只打印出两者之间身份证号较小的员工,并从列表中省略另一个员工。问题是,我该如何修复它,如果这个代码必须修复我的员工档案?这是我的员工代码。任何提示/链接/建议都是有帮助的。

public class Employee implements Comparable {
private String firstName; 
private String lastName;
private int id;
private int perfScale;

Employee() {
firstName = "";
lastName = "";
id = 0;
perfScale = 0;
}

Employee(String lastName, String firstName, int id, int perfScale){
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.perfScale = perfScale;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
public int getPerfScale() {
return perfScale;
}
public void setPerfScale(int perfScale){
this.perfScale = perfScale;
}
public boolean equals(Object o) {
if(o instanceof Employee)
    return(getLastName() == ((Employee) o) .getLastName()) &&
        (getFirstName() == ((Employee)o) .getFirstName());
else
    return false;
}

public int compareTo(Object o) {
Employee e = (Employee) o;
int performance1 = e.getPerfScale();
int performance2 = this.getPerfScale();

if(performance1 < performance2) {
    return 1;

} else if(performance1 > performance2) {
    return -1;
} else {
    return this.getLastName().compareTo(e.getLastName());
}
}

public int hashCode() {
int h1 = firstName.hashCode();
int h2 = lastName.hashCode();
int h3 = new Integer(id).hashCode();
final int HASH_MULTIPLIER1 = 29;
final int HASH_MULTIPLIER2 = 19;
final int HASH_MULTIPLIER3 = 17;
int h = HASH_MULTIPLIER1 * h1 + HASH_MULTIPLIER2 * h2 + HASH_MULTIPLIER3 * h3;
return h;
}

public String toString()
{
    return getLastName() + ", " + getFirstName() + " ," + getId() + " rating: " +     getPerfScale()+ " Performance Scale";

}
    }

现在这只是我处理按升序排序的案例的代码。整个代码比我打印的代码长,所以我只打印它产生排序的情况。

public static void printLastNameAscending(TreeMap<String, Employee> LastName,
        TreeMap<Integer, Employee>idNumber) {
    Set Employee1 = LastName.entrySet();
    Set Employee2 = idNumber.entrySet();
    Iterator itr1 = Employee1.iterator();
    Iterator itr2 = Employee2.iterator();

    while (itr1.hasNext() && itr2.hasNext()) {
        Map.Entry me = (Map.Entry) itr1.next();
        Map.Entry be = (Map.Entry) itr2.next();
        System.out.print(me.getKey()+ " ID: ");
        System.out.println(be.getKey());
    }

}
4

1 回答 1

1

但问题是,如果这两个员工的名字也相同,那么它必须按 ID 号排序,而事实并非如此。

compareTo不会对 ID 号或名字做任何事情。事实上,它首先使用性能。

我的代码:如果两个员工的全名相同但身份证号不同,那么它只打印出两者之间身份证号较小的员工,并从列表中省略另一个员工。问题是,我该如何修复它,如果这个代码必须修复我的员工档案?这是我的员工代码。任何提示/链接/建议都是有帮助的。

查看您的equals函数是否存在问题:如果名字和姓氏相同,您的地图认为两个员工是相同的。您应该重写您的equals函数以同时考虑employeeID。

于 2013-10-28T13:56:22.847 回答