java - Sorting a list of constructed objects alphabetically using collections.sort -
i need take collection of objects using compareto() command, , have these stored in list, , use collections.sort() command sort them alphabetically last name, first name if last name isn't strong enough, , print off entire list @ end.
this code have 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 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; } }
first of add getters first , last name. try 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 tostring() method student class:
@override public string tostring() { return f+" "+l+", "+a; }
Comments
Post a Comment