我编写了如下代码,使用 Comparator 根据姓氏进行排序:
class Order{
private static ArrayList<String> personlist = new ArrayList<String>();
Iterator iter1 = personlist.iterator();
while (iter1.hasNext()) {
System.out.println(iter1.next());
}
Collections.sort(personlist, new LastnameComparator());
Iterator iter2 = personlist.iterator();
while (iter2.hasNext()) {
System.out.println(iter2.next());
}
}
class String implements Comparable {
String firstName, lastName;
public String(String f, String l) {
this.firstName = f;
this.lastName = l;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return "[ firstname=" + firstName + ",lastname=" + lastName + "]";
}
public int compareTo(Object obj) {
String emp = (String) obj;
int comp = firstName.compareTo(emp.getFirstName());
return ((comp == 0) ? lastName.compareTo(emp.getLastName()) : comp);
}
public boolean equals(Object obj) {
if (!(obj instanceof String)) {
return false;
}
String emp = (String) obj;
return firstName.equals(emp.getFirstName()) && lastName.equals(emp.getLastName());
}
}
class LastnameComparator implements Comparator<String> {
@Override
public int compare(String lastname1, String lastname2) {
int lnameComp = lastname1.getLastName().compareTo(lastname2.getLastName());
return ((lnameComp == 0) ? lastname1.getFirstName().compareTo(lastname2.getFirstName()) :
lnameComp);
}
}
但是这段代码不能正常工作并给我错误。personlist 包含以下名称:
John C. Shafer
Ariel Fuxman
Roberto J. Bayardo Jr.
Alexandre V. Evfimievski
Dmitri Asonov
Kristen LeFevre
我希望它以下列方式显示
Dmitri Asonov
Alexandre V. Evfimievski
Ariel Fuxman
Roberto J. Bayardo Jr.
Kristen LeFevre
John C. Shafer
我应该在这段代码中做什么来修复它?谢谢。