Results 1 to 4 of 4
Thread: comparator to compare class year
- 10-19-2010, 05:14 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
comparator to compare class year
i am given a set of student data and i have to sort the data by the class year(freshman, sophomore, and etc). but since freshman, sophomore, junior, and senior are not in alphabetical order, i get freshman, junior, senior, and sophomore. how should i change the code so that the output would go from freshman->sophomore->junior->senior, and not the alphabetical order of the class year?
Thanks in advance!
- 10-19-2010, 05:27 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Mhm... use an enum type for the class years.
Then you are able to use the compareTo from enum class :p
(or you save the Strings/class years in an array and in your compareTo/compare method you compare the indices e.g. freshman = String[0] < sophomore in String[1])
- 10-19-2010, 05:34 PM #3
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
i have the class year in an array of objects
and this is what i have for my comparator now
Java Code:public int compare(Student a, Student b){ return a.getclass().compareTo(b.getclass()); }
- 10-19-2010, 05:45 PM #4
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
...i would use an enum :)
maybe something like:
Java Code:enum CLASS_YEAR{ FRESHMAN,SOPHOMORE,JUNIOR,SENIOR; public String toString() { return this.name().toLowerCase(); }; } class ClassYearComparator implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { return o1.getYear().compareTo(o2.getYear()); } } class Student{ private CLASS_YEAR year; //..... public Student(/* ... */ CLASS_YEAR year) { this.year = year; } /** * @return the year */ public CLASS_YEAR getYear() { return year; } //...... }
Similar Threads
-
how to use comparator
By KidneyinaCooler in forum Advanced JavaReplies: 2Last Post: 07-18-2010, 10:25 AM -
compare items in Purse class, regardless of order
By Jojogamer in forum New To JavaReplies: 0Last Post: 03-14-2010, 06:57 PM -
Date of first day, given the week in the year and the year...
By Lee.J.Baxter in forum Advanced JavaReplies: 1Last Post: 08-26-2009, 08:48 AM -
Use different comparator for SortedSet
By linus_k in forum New To JavaReplies: 0Last Post: 11-21-2008, 02:46 PM -
How to write your own Comparator
By Java Tip in forum java.langReplies: 0Last Post: 04-15-2008, 07:38 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks