Comparator Implementation

4 views
Skip to first unread message

Jesse Chezenko

unread,
Apr 21, 2011, 6:19:48 PM4/21/11
to UBC CPSC 210
I'm looking over the MapsRecommenderComplete package and in the
CourseRecommender class there is the option to construct a tree map
given natural ordering or ordering defined by the CourseNumComparator
class.

The Comparator Interface documentation states that equals() should be
be consistent with with the compare() method.

It seems as if course equality is based on the dept field and the num
field.
In contrast, the CourseNumComparator compare method is based strictly
on course number.
So a Course object with different dept fields and common num fields
means the compare method will return true while the equals method will
return false.

I'd like to suggest changing the equals method to just be based on num
field but then the treemap could not have different subjects with the
same course number( I think ).

http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html
http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html

Paul Carter

unread,
Apr 21, 2011, 7:47:03 PM4/21/11
to ubc-cp...@googlegroups.com
Good question.

Note that the documentation for the Comparator interface doesn't state that the compare() method MUST be consistent with equals() but this IS recommended and the documentation warns to be careful if these methods are not consistent.

In our case, when we use the Comparator rather than the natural ordering defined by Comparable, we don't observe the "strange" behaviour alluded to in the documentation for Comparator because the course numbers happen to be unique for the keys (not the values) in the recommender. Admittedly, we got lucky here. We will run into problems if we try to add two courses from different departments with the same course number as keys to the recommender - try it! The second course will not be added as a key because there's already a key in the map with the same course number.

This is a great observation but goes beyond what I'd expect you to deal with in this course.

Paul

Reply all
Reply to author
Forward
0 new messages