2. Why Generic Programming
Generic programming means writing code that can be reused for objects of many
different types.
For example, you don’t want to program separate classes to collect String and File
objects. And you don’t have to—the single class ArrayList collects objects of any
class. This is one example of generic programming.
3. Defining a Simple Generic Class
public class SomeClass<T>
{
private T someProperty;
public SomeClass() { someProperty = null;}
public SomeClass(T someProperty) { this. someProperty = someProperty;}
public T getSomeProperty() { return someProperty; }
public void setSomeProperty(T newValue) {someProperty = newValue; }
}
USAGE: SomeClass<String>
public class MyEntry<T,U>
{
private T key;
private U value;
public MyEntry() { key = null; value = null; }
public MyEntry(T key, U value) { this.key = key; this.value = value; }
public T getKey() { return key; }
public U getValue() { return value; }
public void setKey(T newKey) { key = newKey; }
public void setValue(U newValue) { value = newValue; }
}
USAGE: MyEntry<String,Integer>
4. Generic Methods
We can also define a single method with type parameters.
Example:
class ArrayAlg {
public static <T> T getMiddle(T... a) {
return a[a.length / 2];
}
}
USAGES:
ArrayAlg.<String>getMiddle("John", "Q.", "Public");
ArrayAlg.getMiddle("John", "Q.", "Public");
ArrayAlg.getMiddle(3.14, 1729, 0);
5. Smart Java
C++ NOTE: In C++, you place the type parameters after the method name. That
can lead to nasty parsing ambiguities. For example, g(f<a,b>(c)) can mean “call g
with the result of f<a,b>(c)”, or “call g with the two boolean values f<a and b>(c)”.
6. Bounds for Type Variables
Sometimes, a class or a method needs to place restrictions on type variables.
For example we want to find the minimum element of an array but we are passing
not comparable types into generic, for this case there is bounding for types.
Example: <T extends BoundingType>
Notice: here we have keyword extends instead of implements for interfaces
7. Bounds for Type Variables
A type variable or wildcard can have multiple bounds.
Example: T extends Comparable & Serializable
The bounding types are separated by ampersands (&) because commas are used to separate type
variables.
As with Java inheritance, you can have as many interface supertypes as you like,but at most one of the
bounds can be a class. If you have a class as a bound, it must be the first one in the bounds list.
9. Processes in Virtual Machine
• TYPE ERASURE
• TRANSLATING GENERIC METHODS
• CALLING LEGACY CODE
10. Type Erasure
Whenever you define a generic
type, a corresponding raw type is
automatically provided. The
name of the raw type is simply
the name of the generic type,
with the type parameters
removed. The type variables are
erased and replaced by their
bounding types (or Object for
variables without bounds).
Replace all type parameters in generic types with their bounds
or Object if the type parameters are unbounded. The produced
bytecode, therefore, contains only ordinary classes, interfaces, and
methods.
Insert type casts if necessary to preserve type safety.
Generate bridge methods to preserve polymorphism in extended
generic types.
Type erasure ensures that no new classes are
for parameterized types; consequently, generics
no runtime overhead.
11. Translating
Generic
Methods Type erasure also happens for generic
methods. Programmers usually think of a
generic method such as
public static <T extends Comparable> T min(T[]
a)
as a whole family of methods, but after erasure,
only a single method is left:
public static Comparable min(Comparable[] a)
Note that the type parameter T has been
erased, leaving only its bounding type
Comparable. Erasure of methods brings up a
couple of complexities.
Bridge Methods
Covariant return types
12. In summary about translation
of Java
There are no generics in the virtual machine, only ordinary classes and methods.
All type parameters are replaced by their bounds.
Bridge methods are synthesized to preserve polymorphism.
Casts are inserted as necessary to preserve type safety.
13. Calling Legacy
Code
void
setLabelTable(Dictionar
y table)
slider.setLabelTabl
e(labelTable); //
Warning
@SuppressWarnings("u
nchecked")
Dictionary<Integer,
Components>
labelTable =
slider.getLabelTable(); //
No warning
Dictionary<Integer,
Components>
labelTable =
slider.getLabelTable();
// Warning
When we use generic
without raw type. It is need
when we have code in which
somewhere isn’t supported
new implementation of
generics . So we receive
warning from compiler.
14. Restrictions and Limitations
• TYPE PARAMETERS CANNOT BE INSTANTIATED WITH PRIMITIVE TYPES
• RUNTIME TYPE INQUIRY ONLY WORKS WITH RAW TYPES
• YOU CANNOT CREATE ARRAYS OF PARAMETERIZED TYPES
• VARARGS WARNINGS
• YOU CANNOT INSTANTIATE TYPE VARIABLES
• YOU CANNOT CONSTRUCT A GENERIC ARRAY
• TYPE VARIABLES ARE NOT VALID IN STATIC CONTEXTS OF GENERIC CLASSES
• YOU CANNOT THROW OR CATCH INSTANCES OF A GENERIC CLASS
• YOU CAN DEFEAT CHECKED EXCEPTION CHECKING
• BEWARE OF CLASHES AFTER ERASURE