简体   繁体   中英

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.

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. It would never occur to me to compare hashCodes.

If you want to ignore case, you can use 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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