繁体   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