Generics
Objective
- use Java generics to encourage code reuse
Notes
- generics allow one method to be used with several different data types
- something similar can be done writing code using a supertype for all objects that will be passed to a method,
but generics improve this by adding some checking at compile time to check type safety
- both classes and methods can use generics to become more general
- unlike C++, there is only one copy of a generic method produced in the finished bytecode (C++
produces one copy at compile time for each data type used to call the method in the code)
- a procedure called erasure replaces all generic types with actual types in the compiled
bytecode; the default type for this is Object
- generic arguments are required to be generic, but algorithms often call for using primitive
(built-in) data types; this isn't a big problem since all of the primitive data types in Java
have corresponding wrapper classes (such as Integer for int)
- Java's autoboxing and unboxing feature usually makes it easy to use wrapper classes such as
Integer in place of their corresponding built-in type (in this case int)
- Java generics can use wildcards (see the demonstration programs)
- ? extends ClassA: allows subclasses of ClassA
- ? super ClassA: allows superclasses of ClassA
- you can use multiple bounds: T extends Comparable & Serializable
- always put the most used bound first when using multiple bounds (for efficiency)
- arrays of parameterized types are not allowed
- you cannot use instantiation of a parameterized type such as: new T()
Demonstration programs