Comparing things Comparable & Comparator
Maybe we are jumping the gun a bit here but please live with it for a while. We are wanting to implement a set of “things” of the same class obviously A set disallows duplicates. So, when we add something to the set we must make sure it is not already in the set. Consequently we need to be able to compare “things”. There are, broadly, 2 ways to do this
preliminaries We are going to use two classes from java.util TreeSet HashSet
TreeSet
HashSet
Comparable
Comparable We want to create a set of people (class Person) where a Person has a first and second name
Comparable
Comparable
Comparable
Comparable It’s comparable
Comparable x.compareTo(y)
Comparable
Comparable Duplicate not added
Comparable Same again but Species rather than Person
Comparable Duplicate avoided
Comparator
Comparator We now look at an alternative, the Comparator, an object that is used to make comparisons Our example uses cars
Comparator
Comparator
Comparator
Comparator
Comparator
Comparator Duplicate omitted
Comparator
Comparator Why do we get duplicates?
HashSet v TreeSet
HashSet doesn’t allow us to use Comparable or Comparator Why?