簡體   English   中英

使用collections.sort按字母順序對構造對象列表進行排序

[英]Sorting a list of constructed objects alphabetically using collections.sort

我需要使用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;
    }

}

如果要按字母順序比較它們,請使用String.compareTo方法。 比較hashCodes對我來說永遠不會發生。

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

首先,我將為名字和姓氏添加吸氣劑。 然后嘗試以下代碼:

@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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM