好吧,我还需要修复一个问题。我的hashmap代码添加/删除/修改/打印/排序(有点)。这是排序问题。它按姓氏按升序排序。如果两个员工具有相同的姓氏,那么它将按名字继续提升。但问题是,如果两个员工的名字相同,那么它必须按ID号排序,但不是。
我的代码:如果两名员工具有相同的全名但ID号不同,那么它只会打印出两者之间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());
}
}
答案 0 :(得分:1)
问题是,如果两名员工的姓氏相同,那么必须按ID号排序,而不是。
您的compareTo
对身份证号码和名字不做任何处理。实际上,它首先使用性能。
我的代码:如果两名员工具有相同的全名但ID号不同,那么它只会打印出两者之间ID号较小的员工,并从列表中省略另一名员工。问题是,我该如何解决它,如果这个代码必须修复我的员工档案?这是我的员工代码。任何提示/链接/建议都是有帮助的。
查看问题的equals
函数:如果名字和姓氏相同,您的地图会认为两名员工是相同的。您应该重写equals
函数以考虑employeeID。