优先队列排序字符串

Priority Queue Sorting String

我需要使用 PriorityQueue 对 Person 对象进行排序。

这个人 class:

    public class Person implements Comparable<Person>{
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName){
       this.firstName = firstName;
       this.lastName = lastName;
    }

    public String getFirstName() {return firstName;}

    public String getLastName() {return lastName;}

    public String toString(){
       return "Name: " + firstName + " " + lastName + "\n";
    }

    public int compareTo(Person p){
       String pname1 = firstName + lastName;
       String pname2 = p.firstName + p.lastName;
       return pname1.compareTo(pname2);
    }

主要代码:

    import java.util.PriorityQueue;

    public class priorityQ{
        public static void main(String[] args){
           PriorityQueue<Person> pers = new PriorityQueue<Person>();
           pers.add(new Person("Sam", "Smith"));
           pers.add(new Person("Charlie", "Black"));
           pers.add(new Person("Betty", "Brown"));
           pers.add(new Person("Jessica", "Stewart"));
           pers.add(new Person("John", "Friday"));
           pers.add(new Person("Frank", "Folcy"));
           System.out.print(pers);      
       }   
    }

我需要:

  1. 不排序打印(已在 main 中完成)
  2. 按姓氏排序
  3. 先按名字排序,然后按姓氏排序

我不能更改 Person class 中的任何代码。

我创建了新的 class:

    import java.util.Comparator;
    public class LastNameComparator implements Comparator<Person>{
       public int compareTo(Person a, Person b){
         Person p1 = (Person)a;
         Person p2 = (Person)b;
         if(p1.getLastName().equals(p2.getLastName()))
         {
            return p1.getFirstName().compareTo(p2.getFirstName());
         }
         return p1.getLastName().compareTo(p2.getLastName());
       }
    }

编译错误:

LastNameComparator.java:2: error: LastNameComparator is not abstract and does not override abstract method compare(Person,Person) in Comparator

首先: 请删除

implements Comparable<Person>

 public int compareTo(Person p){
       String pname1 = firstName + lastName;
       String pname2 = p.firstName + p.lastName;
       return pname1.compareTo(pname2);
    }

来自 Person class,因为您不能大声对其进行任何更改。

第二: 比较器 Class 只有 compare(T ob1, T2 ob2) 方法,没有 public int compareTo(Person a, Person b)。 所以请创建 compare(T ob1, T2 ob2) 并在其上添加 @Override 注释以确保您做的一切都是正确的。

所以毕竟你的比较器class必须是

@Override
public int compare(Person a, Person b){
//..your code
}

其余代码看起来不错,从快速看...

首先,您必须从 person class 及其所有实现中删除 comparable interface: 尝试这样做:

import java.util.Comparator;
    public class LastNameComparator implements Comparator<Person>{    
    @Override
    public int compare(Person o1, Person o2) {

        return o1.lastname.compareTo(o2.lastname);
    }
    }

然后在 main method 中执行以下操作以按姓氏排序:

Collections.sort(pers,new LastNameComparator());
    Iterator<Person> it = pers.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
       }