Ben’s Lecture Cliff Notes Generic Functions • I want to write generic functions, so I don’t have to rewrite them again. • The problem is functions often depend on functionality provided by the parameters. • How can I write a generic function, using generic parameters, yet those parameters are mandated to have certain functionality? – Answer: Interfaces (a contract of functionality) • Required methods, but the definition is up to the user. A Generic Sort • To write a generic sort, I need to be able to compare the objects I am asked to sort. • Each object must have a function to compare itself with another object. – Solution: The sort function accepts a collection of objects that implement the Comparable interface • Comparable objects have a compareTo function. • Now I can sort any collection so long as the objects implement this interface, using one sort function. – Call compareTo for each object in the collection. Problem • The Comparable interface only provides one way to compare. • What if I need diverse mechanisms of comparison? (sort by size, shape, color, ….) • How do I write a generic sort algorithm that can sort the objects by comparing any characteristic? – Answer: Provide the sort a Comparator in addition to the collection Comparator • The Comparator interface contains one method, compare. • The sort function can then use any object that implements the Comparator interface to perform the comparisons desired, and then the sort can sort accordingly. • Sort accepts the collection and the comparator.