user3782738
user3782738

Reputation: 3

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

}

Upvotes: 0

Views: 437

Answers (2)

MichaelS
MichaelS

Reputation: 6042

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

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

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

Upvotes: 3

Related Questions