使用collections.sort按字母顺序对构造对象列表进行排序

时间:2014-06-27 10:27:03

标签: java arrays sorting

我需要使用CompareTo()命令获取对象集合,然后将这些对象存储在列表中,然后使用collections.sort()命令按姓氏的字母顺序排序,然后按名字排序姓氏不够强大,然后在最后打印整个列表。

这是我到目前为止的代码:

package sortlab;
import java.io.*;
import java.util.*;
public class SortLab {
    public static void main(String[] args) throws Exception {
       File youSaidUseOurRelativeFileNameForStudentData = 
            new File("C:/My192/SortLabProj/src/sortlab/student.data");
       Scanner sc = new Scanner(youSaidUseOurRelativeFileNameForStudentData);        
       ArrayList<Student> StudentList = new ArrayList<Student>();
       while (sc.hasNextLine()) {          
            Student testStudent = new Student(sc.next(), sc.next(), sc.next());
            sc.nextLine();
            StudentList.add(testStudent);
       }
    }

}

下一堂课:

package sortlab;
import java.util.*;
class Student implements Comparable<Student> {

    private String first;
    private String last;
    private String address;

    public Student(String f, String l, String a) {
        first = f;
        last = l;
        address = a;
    }

    @Override
    public int compareTo(Student other) {
        if (last.hashCode() > other.last.hashCode()) return 1;
        if (last.hashCode() < other.last.hashCode()) return -1;
        if (first.hashCode() > other.first.hashCode()) return 1;
        if (first.hashCode() < other.first.hashCode()) return -1;
        return 0;
    }

}

2 个答案:

答案 0 :(得分:3)

如果要比较它们,请使用String.compareTo方法。我不会想要比较hashCodes。

如果要忽略大小写,可以使用String.compareToIgnoreCase

答案 1 :(得分:0)

首先,我会为名字和名字添加getter。然后尝试以下代码:

@Override
public int compareTo(Student other) {
    int result = l.compareTo(other.getLastName());
    if (result == 0) {
        return f.compareTo(other.getFirstName());
    } else {
        return result;
    }
}

然后将toString()方法添加到Student类:

@Override
public String toString() {
    return f+" "+l+", "+a;
}