简体   繁体   English

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

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

I need to take a collection of objects using the CompareTo() command, and then have these stored in a list, and then use the collections.sort() command to sort them alphabetically by last name, then by first name if the last name isn't strong enough, and then print off the entire list at the end. 我需要使用CompareTo()命令收集对象,然后将它们存储在列表中,然后使用collections.sort()命令按姓氏对字母进行排序,如果姓氏,则按名字进行排序不够强大,然后最后打印出整个列表。

This is the code I have so far: 这是我到目前为止的代码:

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

}

And the next class: 下一节课:

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

}

If you want to compare them ASCIIbetically use the String.compareTo method. 如果要按字母顺序比较它们,请使用String.compareTo方法。 It would never occur to me to compare hashCodes. 比较hashCodes对我来说永远不会发生。

If you want to ignore case, you can use String.compareToIgnoreCase 如果要忽略大小写,可以使用String.compareToIgnoreCase

First of all I would add getters for first and last name. 首先,我将为名字和姓氏添加吸气剂。 Then try this code: 然后尝试以下代码:

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

Then add a toString() method to your Student class: 然后将toString()方法添加到Student类中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM