generic(parameterized ) types mehdi einali advanced programming in java 1
TRANSCRIPT
1
Generic(Parameterized ) types
Mehdi Einali
Advanced Programming in Java
2
AgendaWhy Generics
Generic MethodsGeneric Classes
Type ErasureGenerics and InheritanceGenerics and Wild CardsRestrictions on Generics
3
Why generics
4
5
Stack interfacesinterface StringStack{
void push(String s);String pop();
}interface IntegerStack{
void push(Integer s);Integer pop();
}interface StudentStack{...
6
Sort Methodstatic void sort(Integer[] array) {// ...
}static void sort(Double[] array) {// ...
}static void sort(String[] array) {// ...
}static void sort(Student[] array){// ...
}
7
The ProblemWhat is wrong with these examples?
Code redundancy No effective code reuse
Solution?Using Object classPros and Cons?
Compile-time type safety
8
Most of time Common properties and controls requiredBut software is not just execution of code developers is very important
Annotations: @Deprecated, @Override, @AuthorWe need some type check just for compile time(for humans not computers)
Compile time vs runtime time
Compile Runtime
9
The SolutionGeneric types and methods
Methods with similar implementation which accepts parameters for impose some restriction on them
Generics provides abstraction over Types (Parameterized Types)
10
Generic stackStack<Havij> stack=new Stack<Havij>();Stack.push(new Havij());Stack.push(new Havij());
Stack<Golabi> stack=new Stack<Golabi>();Stack.push(new Golabi());Stack.push(new Golabi());
11
Why generics?To enable a compiler to as much as error as it can at compile time rather than getting surprised at run time(ClassCastException)
Extended code reusability
Improve readability and robustness
Try to find bugs ASAP!!
12
Generic classes
13
Type parameter as the Return Type
interface Stack<T>{void push(T s);T pop();
}
Stack<String> stringStack = new ...stringStack.push(“salam”);String s = stringStack.pop();
14
public class Stack<E > {private E[] elements ;private final int size; // number of elements in the
stackprivate int top; // location of the top elementpublic void push(E pushValue) {
if (top == size - 1) // if stack is full throw new FullStackException();
elements[++top] = pushValue; }
public E pop() {if (top == -1) // if stack is empty
throw new EmptyStackException();return elements[top--];
}public Stack() {
size = 10; top = -1; elements = new Object[size];
}}
15
Using Stack Class Stack<String> stack1 = new Stack<String>();stack1.push("first");stack1.push("second");System.out.println(stack1.pop());System.out.println(stack1.pop());
Stack<Integer> stack2 = new Stack<Integer>();stack2.push(1);stack2.push(2);System.out.println(stack2.pop());System.out.println(stack2.pop());
16
Compile-time Type CheckingStack<String> stack1 = new Stack<String>();
stack1.push(new Integer(2));
Compile-time error
17
public class Stack<E extends Student> {private E[] elements ;private final int size; // number of elements in the
stackprivate int top; // location of the top element
public void push(E pushValue) {if (top == size - 1) // if stack is full
throw new FullStackException();elements[++top] = pushValue;
} public E pop() {
if (top == -1) // if stack is emptythrow new EmptyStackException();
return elements[top--]; }public Stack() {
size = 10; top = -1; elements = new Student[size];
}}
18
Generic methods
19
Generic MethodsDeclaring a method which accepts different parameter types
For each method invocation, the compiler searches the appropriate methodIf the compiler does not find a method, it looks for a compatible generic method
Type Parameter
It says: In this method, E is not a regular type, it is a generic one
20
printArray() Generic Method
21
Benefits of Genericspublic static < E extends Number> void printArray( E[] inputArray ){…}
Restricting possible typesCompile-time type checking
printArray(stringArray) bringsCompiler Erroror exception?
22
You can specify generic type for methods too.
23
Type erasure
24
Raw TypesGeneric classes and methods can be used without type parameterStack<String> s = new Stack<String>();
String as type parameters.push(“salam”);s.push(new Integer(12)); Compiler Error
Stack objectStack = new Stack(); no type parameters.push(“salam”);s.push(new Integer(12));s.push(new Student(“Ali Alavi”));
25
No Generics in RuntimeGenerics is a compile-time aspectIn runtime, there is no generic informationAll generic classes and methods are translated with raw typesByte code has no information about genericsOnly raw types in byte codeThis mechanism is named generic type erasure
26
ErasureWhen the compiler translates generic method into Java bytecodesIt removes the type parameter section It replaces the type parameters with actual types.This process is known as erasure
27
Erasure Example (1)class Stack<T>{
void push(T s){...}T pop() {...}
}
Is translated to
class Stack {void push(Object s){...}Object pop() {...}
}
28
Erasure Example (2)
Translated to
29
What Happens if…
30
Some NotesWe can also create generic interfaces
interface Stack<T>{void push(T s);T pop();
}
31
What Happens if…public static <E extends Number> void f(E i){
}
public static void f(Number i){}
Compiler Error : Method f(Number) has the same erasure version f(Number) as another method in this
type
32
Multiple Type Parametersclass MultipleType<T,K>{
private T t;public T getT() {
return t;}public void setT(T t) {
this.t = t;}public void doSomthing(K k, T t){…}
}MultipleType<String, Integer> multiple =
new MultipleType<String, Integer>();multiple.doSomthing(5, "123");
33
Inheritance and generics
34
Generics and subtypesYou can do this
Object o = new Integer(5);
You can even do thisObject[] or = new Integer[5];
So you would expect to be able to do thisArrayList<Object> ao = new ArrayList<Integer>();This is counter-intuitive at the first glance
35
Why?
So there is no inheritance relationship between typearguments of a generic class
36
This works
Inheritance relationship between genericclasses themselves still exists
37
Still works
Entries in a collection maintain inheritancerelationship
38
Generics and InheritanceA non-generic class can be inherited by a non-generic class
As we saw before learning generics
A generic class can be inherited from a non-generic class
Adding generality to classes
A non-generic class can be inherited from a generic class
Removing generality
A generic class can be inherited by a generic class
39
class GenericList<T> extends Object{public void add(T t){...}public T get(int i) {...}public void remove(int i) {...}
}class GenericNumericList<T extends Number>
extends GenericList<T>{}
class NonZeroIntegerList extends GenericList<Integer>{
public void add(Integer t) { if(t==null || t==0)
throw new RuntimeException(“Bad value"); super.add(t); }
}
40
Generics and Wild card
41
Why Wildcards? ProblemConsider the problem of writing a routine that prints out all the elements in a collection
What is wrong with this?
42
Why Wildcards? SolutionUse Wildcard type argument <?>Collection<?> means Collection of unknown type
43
Bounded wild characterIf you want to bound the unknown type to be a subtype of another type, use bounded Wildcard
44
Restrictions on generic types
45
Not primitive type
Cannot Instantiate Generic Types with Primitive Types
46
Not insatiateCannot Create Instances of Type Parameters
47
Not staticCannot Declare Static Fields Whose Types are Type Parameters
Confusing code:
48
No cast no instaneofCannot Use Casts or instanceof with Parameterized Types
The runtime does not keep track of type parameters, so it cannot tell the difference between an ArrayList<Integer> and an ArrayList<String>.
49
Arrays of Parameterized Types
You cannot create arrays of parameterized type
50
Generics and Java 7Older versions:
ArrayList<String> list = new ArrayList<String>();
With Java 7:ArrayList<String> list = new ArrayList<>();
Type information after new are ignored.
List<Map<Long, Set<Integer>>> list = new ArrayList<>();
51
end