Download presentation
Presentation is loading. Please wait.
1
Comparing things Comparable & Comparator
2
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
3
preliminaries We are going to use two classes from java.util TreeSet HashSet
4
TreeSet
8
HashSet
12
Comparable
13
Comparable We want to create a set of people (class Person) where a Person has a first and second name
14
Comparable
15
Comparable
16
Comparable
17
Comparable It’s comparable
18
Comparable x.compareTo(y)
19
Comparable
20
Comparable Duplicate not added
21
Comparable Same again but Species rather than Person
22
Comparable Duplicate avoided
23
Comparator
24
Comparator We now look at an alternative, the Comparator, an object that is used to make comparisons Our example uses cars
25
Comparator
26
Comparator
27
Comparator
28
Comparator
29
Comparator
30
Comparator Duplicate omitted
32
Comparator
33
Comparator Why do we get duplicates?
34
HashSet v TreeSet
35
HashSet doesn’t allow us to use Comparable or Comparator
Why?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.