Java Reference
In-Depth Information
Understanding Generic Supertypes
You might fi nd it confusing that a FileNotFoundException object can appear in
the exceptions list, especially because FileNotFoundException is not a parent of
IOException . The upper bound of the generic method showExceptions applies to the data
type of the generic, which for <? super IOException> must be a parent class of Exception .
The argument passed in was an ArrayList<Exception> , which is compatible with <? super
IOException> . Because the data type of the generic is ArrayList<IOException> , any child
of Exception can appear in the actual ArrayList , which is why FileNotFoundException
can be in the list. In fact, any child object of Exception can appear in the exceptions object
created on line 30 of the previous code snippet.
This ends our discussion on writing your own generic classes, interfaces, and methods.
Now we change subjects and discuss how to sort and search lists using classes in the
java.util package.
Working with Lists
For the exam you should be able to sort lists either in their natural order or using a
Comparator object. The exam also requires knowledge of performing a binary search on
lists. These objectives are indirectly referring to methods in the java.util.Collections
class. In particular, the objectives refer to the static methods sort and binarySearch in
Collections , which take in a List and an optional Comparator object.
In the next section I discuss the details that you need to know for the exam regarding
the sorting and searching of lists using the Collections class, starting with the sort
methods.
Sorting Lists
The Collections class (not to be confused with the Collection interface) contains
dozens of useful static methods for working with and manipulating collections. The exam
objectives specifi cally state knowledge of sorting lists, which is achieved using the two sort
methods of Collections :
public static <T extends Comparable<? super T>> void sort(List<T> list)
sorts the given List according to its natural ordering, which is the ordering based on
the implementation of the compareTo method in the Comparable interface. The elements
in list must implement Comparable and must be mutually comparable , meaning each
element can be compared to each other element without a ClassCastException being
thrown.
Search WWH ::




Custom Search