-5

我编写了如下代码,使用 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

我应该在这段代码中做什么来修复它?谢谢。

4

2 回答 2

0
public int compareTo(Object obj) {
    String emp = (String) obj;
    int comp = firstName.compareTo(emp.getFirstName());
    return ((comp == 0) ? lastName.compareTo(emp.getLastName()) : comp);
}

应该,

public int compareTo(Object obj) {
    String emp = (String) obj;
    int comp = lastName.compareTo(emp.getLastName());
    return ((comp == 0) ? firstName.compareTo(emp.getFirstName()) : comp);
}

// 你也应该避免将一个类命名为 String

于 2013-03-17T19:10:07.863 回答
-2

注意如果您执行以下代码之类的操作,世界实际上将在几秒钟内结束!请不要怪我,我警告过你。

只需使用 normal Strings 并使用这样的自定义 Comparator :

public class PersonComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
        String[] o1Data = o1.split(" ");
        String[] o2Data = o2.split(" ");
        String o1Last = o1Data[o1Data.length-1];
        String o2Last = o2Data[o2Data.length-1];
        return o1Last.compareTo(o2Last);
    }
}

只需提取名称的最后一部分,然后比较它们。

于 2013-03-17T18:59:04.630 回答