Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comparing things Comparable & Comparator.

Similar presentations


Presentation on theme: "Comparing things Comparable & Comparator."— Presentation transcript:

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

5

6

7

8 HashSet

9

10

11

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

31

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?

36


Download ppt "Comparing things Comparable & Comparator."

Similar presentations


Ads by Google