Results 1 to 5 of 5
Thread: compareTo method
- 04-21-2011, 04:23 PM #1
Member
- Join Date
- Apr 2011
- Location
- USA
- Posts
- 15
- Rep Power
- 0
compareTo method
Assuming there are methods called getLast() and getFirst()
I don't know how to interpret the method body. I know there is another way to write this code, but I am not sure what that is.Java Code:public int compareTo(Object n) { Student s = (Student)n; int num = lastname.compareTo(s.getLast()); return (num != 0 ? num : firstname.compareTo(s.getFirst())); }
-
[ignore]I don't think you should be using getLast or getFirst (did your teacher suggest this, or if not, what are you trying to achieve by using this?) but rather simply comparing the current object with n.[/ignore]
Edit: Please ignore this dreck that I've posted above. -- I was not thinking but thought that you were getting the last or first items from a list not first and last names. :(Last edited by Fubarable; 04-21-2011 at 04:38 PM.
- 04-21-2011, 04:31 PM #3
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
It compares two Student objects by their last names. If these are equal, it will compare their first names!
-
sort a List of students "studentList" by first name:
compareToIgnoreCase returns:Java Code:Collections.sort(studentList, new Comparator(){ public int compare(Object o1, Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; int num = s1.getFirstName().compareToIgnoreCase(s2.getFirstName()); boolean equal = num == 0; return equal? s1.getLastName().compareToIgnoreCase(s2.getLastName()) : num; } });
a negative integer, zero, or a positive integer as the the specified String is greater than, equal to, or less than this String, ignoring case considerations.Last edited by ozzyman; 04-21-2011 at 04:38 PM. Reason: added last name comparison
- 04-21-2011, 04:49 PM #5
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Similar Threads
-
Doubt About CompareTo method() ?
By makpandian in forum New To JavaReplies: 8Last Post: 03-08-2011, 06:19 AM -
using the compareTo method
By anonymous445 in forum New To JavaReplies: 3Last Post: 01-19-2011, 03:53 AM -
need help wit this compareTo method
By ShinTec in forum New To JavaReplies: 4Last Post: 02-02-2010, 02:24 AM -
ArrayLists compareTo method, equals method
By random0munky in forum New To JavaReplies: 2Last Post: 10-26-2009, 07:20 PM -
how compareTo Method works
By nanaji in forum Advanced JavaReplies: 1Last Post: 06-22-2008, 07:40 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks