|
Parameterized Classes (and Interfaces)
in Java |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
Person class (that does not
include an ID) and we want to be able to associate
an ID with each Person object
Object as a common
ancestor
Object can be "identified"Object returned by the getEntity()
method will need to be typecast to be used
Object improperly
which will result in a ClassCastException
being thrown at runtime
public class Identified<T>
Object
is appropriate
Identified i;, Identified is the
raw type of Identified<T> )
E - elementK - keyN - numberT - typeV - value
public static <E> void fillArray(E[] a, E e)
extends,
followed by the bounding types (separated by an &)extends was probably a bad choice
since any class that either extends the bounding type or
implements the bounding type can be used (which is why
there can be more than one)
This allows us to avoid the risky typecast that we needed in
the compareTo() method in the class that realized the
interface.
Statistics class with
min() and max() methods
that had to return an Ordered
Comparable<T>, but
we want them to return a T
Comparator Interface
Comparator:
Person objects based on
height or weight
Course objects based on
ID or credit hours
Comparable and Comparator
interfaces can be used to do more than find the minimum and
maximum, they can be used to sortjava.util.Arrays Class:
sort() methods that
take advantage of this observation
Comparator (cont.)
Comparator
Comparator (cont.)
? extends Type
? super Type