How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
Comparator
Collapse
X
-
If there is a natural ordering you can have the class implement Comparable:Originally posted by mia023How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
Comparable API
And in general, you can define a Comparator:
Comparator API
Despite their similar names, don't confuse them. For example, String is Comparable, because there is a natural ordering on Strings; the String class also provides the Comparator CASE_INISENSITI VE_ORDER to allow you to compare pairs of string, ignoring their case.
CASE_INSENSITIV E_ORDER API
Also, check out Sun's tutorial on this:
Collection Algorithms -
IIRC, comparators just compare two items and return a negative number, a positive number or zero if they are equivalent.Originally posted by mia023How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
If I want to use an array to solve this problem How can I do that??
Since strings have a built in comparator all you need to do is implement the comparator in your student class and use the last name string data and compare it and pass up the result.Comment
-
You posted this question yesterday.Originally posted by mia023How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
If I want to use an array to solve this problem How can I do that??
yesterday's postComment
-
One way is to use the utility class java.util.Array s:Originally posted by mia023If I want to use an array to solve this problem How can I do that??
java.util.Array sComment
Comment