小编Mar*_*uer的帖子

Java Collections.sort()未按预期排序

我试图通过特定的属性("程序"的"学生"对象和"教师"的"教授"对象)对对象的两个不同的数组列表进行排序.这两个类都扩展了我的抽象'Person'类.

public abstract class Person implements Comparable<Person>{
    private String name;
    private String adress;

    //getters, setters, etc., all works properly

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); 
    }

    public int compareTo(String string) {
        return name.compareTo(string);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当我创建一个1000000个随机"人物"对象的数组而不是学生或教授时,我决定按照它们的名字(按字母顺序)按字母顺序排序(它可以正常工作).

Person personByName[] = arrayPersonas.clone();
Arrays.sort(personByName);
Run Code Online (Sandbox Code Playgroud)

然后,我将原始Person数组分成两个ArrayLists,一个用于Student对象,另一个用于Professor对象:

    ArrayList<Student> studentsByProgram = new ArrayList();
    ArrayList<Professor> professorsByFaculty = new ArrayList();
    for (int i = 0; i < 1000000; i++) { 
        if (arrayPersonas[i] instanceof Student) {
            studentsByProgram.add((Student)arrayPersonas[i]);
        } else {
            professorsByFaculty.add((Professor)arrayPersonas[i]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试按照我想要的属性按字母顺序对每个ArrayList进行排序时会出现问题,因为它会按Person的名称对它们进行排序:

Collections.sort(studentsByProgram);
Collections.sort(professorsByFaculty); …
Run Code Online (Sandbox Code Playgroud)

java sorting collections comparable comparator

6
推荐指数
1
解决办法
435
查看次数

标签 统计

collections ×1

comparable ×1

comparator ×1

java ×1

sorting ×1