Generic(Parameterized ) Types Advanced Programming in Java Generic(Parameterized ) Types
Agenda Why Generics Generic Methods Generic Classes Type Erasure Generics and Inheritance Generics and Wild Cards Restrictions on Generics
Why generics
Stack interfaces interface StudentStack{... interface StringStack{ void push(String s); String pop(); } interface IntegerStack{ void push(Integer s); Integer pop(); interface StudentStack{...
Sort Method static void sort(Integer[] array) { // ... } static void sort(Double[] array) { static void sort(String[] array) { static void sort(Student[] array){
The Problem What is wrong with these examples? Solution? Code redundancy No effective code reuse Solution? Using Object class Pros and Cons? Compile-time type safety
Compile time vs runtime time Most of time Common properties and controls required But software is not just execution of code developers is very important Annotations: @Deprecated, @Override, @Author We need some type check just for compile time(for humans not computers)
The Solution Generic types and methods Methods with similar implementation which accepts parameters for impose some restriction on them Generics provides abstraction over Types (Parameterized Types)
Generic stack Stack<Havij> stack=new Stack<Havij>(); Stack.push(new Havij()); Stack<Golabi> stack=new Stack<Golabi>(); Stack.push(new Golabi());
Why generics? Try to find bugs ASAP!! To enable a compiler to as much as error as it can at compile time rather than getting surprised at run time (e.g. ClassCastException) Extended code reusability Improve readability and robustness Try to find bugs ASAP!!
Generic classes
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();
public class Stack<E > { private E[] elements ; private final int size; // number of elements in the stack private 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 empty throw new EmptyStackException(); return elements[top--]; public Stack() { size = 10; top = -1; elements = new Object[size];
Using Stack Class Stack<String> stack1 = new Stack<String>(); stack1.push("first"); stack1.push("second"); System.out.println(stack1.pop()); Stack<Integer> stack2 = new Stack<>(); stack2.push(1); stack2.push(2); System.out.println(stack2.pop()); Since V 7 Diamond
Compile-time Type Checking Stack<String> stack1 = new Stack<String>(); stack1.push(new Integer(2)); Compile-time error
public class Stack<E extends Student> { private E[] elements ; private final int size; // number of elements in the stack private 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 empty throw new EmptyStackException(); return elements[top--]; public Stack() { size = 10; top = -1; elements = new Student[size];
Naming Conventions By convention, type parameter names are single, uppercase letters The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types
Generic methods
Generic Methods Declaring a method which accepts different parameter types For each method invocation, the compiler searches the appropriate method If 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
printArray() Generic Method
Benefits of Generics public static < E extends Number> void printArray( E[] inputArray ){…} Restricting possible types Compile-time type checking printArray(stringArray) brings Compiler Error or exception?
You can specify generic type for methods too.
Type erasure
Raw Types Generic classes and methods can be used without type parameter Stack<String> s = new Stack<String>(); String as type parameter s.push(“salam”); s.push(new Integer(12)); Compiler Error Stack objectStack = new Stack(); no type parameter s.push(new Integer(12)); s.push(new Student(“Ali Alavi”));
No Generics in Runtime Generics is a compile-time aspect In runtime, there is no generic information All generic classes and methods are translated with raw types Byte code has no information about generics Only raw types in byte code This mechanism is named generic type erasure
Erasure Example (1) class Stack<T>{ void push(T s){...} T pop() {...} } Is translated to class Stack { void push(Object s){...} Object pop() {...}
Erasure Example (2) Translated to
What Happens if…
Some Notes We can also create generic interfaces interface Stack<T>{ void push(T s); T pop(); }
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
Multiple Type Parameters class 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");
Inheritance and generics
Generics and subtypes You can do this You can even do this Object o = new Integer(5); You can even do this Object[] or = new Integer[5]; So you would expect to be able to do this ArrayList<Object> ao = new ArrayList<Integer>(); This is counter-intuitive at the first glance
Why? So there is no inheritance relationship between type arguments of a generic class in assignment
This works Inheritance relationship between generic classes themselves still exists
Still works Entries in a collection maintain inheritance relationship
Generics and Inheritance A 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
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);
Generics and Wild card
Why Wildcards? Problem Consider the problem of writing a routine that prints out all the elements in a collection What is wrong with this?
Why Wildcards? Solution Use Wildcard type argument <?> Collection<?> means Collection of unknown type
Bounded wild character If you want to bound the unknown type to be a subtype of another type, use bounded Wildcard
Restrictions on generic types
Not primitive type Cannot Instantiate Generic Types with Primitive Types
Not insatiate Cannot Create Instances of Type Parameters
Not static Cannot Declare Static Fields Whose Types are Type Parameters Confusing code:
No cast no instaneof Cannot 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>.
Arrays of Parameterized Types You cannot create arrays of parameterized type
Generics and Java 7 Older 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<>();
end