

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Name:
The biggest transformation of computer programming in the past two decades has been the emphasis on novel approaches to software reuse. Can we find techniques that will allow new applications to be created from existing software components without having to write each new line of code from scratch? You have seen how polymorphism is one part of this topic. A polymorphic variable can be declared as one type but hold a value of a child class type. For example, a variable declared as Object can hold any reference type: Object element = new BankAccount(); Sorting algorithms add a new twist to this problem. How can we create a sorting algorithm, one that can be reused without having to be rewritten, without knowing what type of element is being sorted or how comparisons are determined? The polymorphic variable solves the first part โ simply sort an array of Object values. For the second problem Java introduces a new type of object, termed a Comparator. A Comparator implements the following interface: interface Comparator { int compare (Object left, Object right); } An instance of this class takes two objects and returns a value that is less than zero if the left is smaller than the right, equal to zero if they are equal, and greater than zero if the left is larger than the right. By testing the result value the ordering of the arguments can be determined. Here is the selection sort algorithm rewritten to use comparators: public void selectionSort (Object [] storage, Comparator test) { for (int position = storage-length โ 1; position > 0; position--) { int indexLargest = 0; for (int i = 1; i <= position; i++) { if (test.compare(storage[i], storage[indexLargest]) > 0) indexLargest = i; } if (indexlargest != position) swap(storage, indexLargest, position); } } Now the same code can be used to sort any array of object values.
Name: Imagine that we have an Employee data structure defined as follows: class Employee { public String name; public int salary; public int startingYear; } Write two different comparator classes. The first should take two Employee objects and compare then according to their salary. The second should take two Employee objects and compare them according to their name. For the latter you can use the function String.compareTo(String), which returns an integer value with the same properties we are looking for. class SalaryComparator implements Comparator { public int compare(Object left, Object right) { } } class NameComparator implements Comparator { public int compare (Object left, Object right) { } }