Question --- when I sort a list of object "Student", since "Student' object contains "Address", and both of them implement Comparator, when "student" object list is sorted, does it automatically sort the associated "Address" objects using the "Address" compare rule ? or does it just sort 'student" obj list using its own rule without looking at "address"'s 'compare' rule ?
On a related subject, I see "return -1;" after your conditional statement.
Since Java does not support using numerical values for T/F conditions,
a boolean (or Boolean) should always be used for this purpose.
Jim ... ...
Ernest Friedman-Hill
,
author and iconoclast
staff
Jim Hoglund wrote:On a related subject, I see "return -1;" after your conditional statement.
Since Java does not support using numerical values for T/F conditions,
a boolean (or Boolean) should always be used for this purpose.
Well, no. The compareTo()/compare() methods in Comparable and Comparator, respectively, return an int, so that's what he's returning. Each methods compares two objects and returns a negative number if the first one is "first", 0 if they're "the same" and a positive number if the second one should come first. His pseudocode leaves the "int" return type declaration off of his method -- this is an argument for why you should always PostRealCode .
why I should use comparable instead of comparator ? I read (can't remember where) comprable is more like for natural order and comparator is for customized order, is that true ?
Ernest Friedman-Hill
,
author and iconoclast
staff
If you have a class X, and you want to compare instances of X, you can do one of two things:
1) have X implement Comparable<X>, and then you can call "x1.compareTo(x2)"
2) create some other class entirely Z, and have it implement Comparator<X>; then you can call z.compare(x1, x2)
What you've done is create a situation where you can call x3.compare(x1, x2), and while it does work, it really doesn't make much sense. That object "x3" shouldn't be involved in the comparison. If you want a third object to compare two Xs, then make it an instance of another class. If you want one X to compare itself to another, then use Comparable.