Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generic(Parameterized ) Types

Similar presentations


Presentation on theme: "Generic(Parameterized ) Types"— Presentation transcript:

1 Generic(Parameterized ) Types
Advanced Programming in Java Generic(Parameterized ) Types

2 Agenda Why Generics Generic Methods Generic Classes Type Erasure
Generics and Inheritance Generics and Wild Cards Restrictions on Generics

3 Why generics

4 Stack interfaces interface StudentStack{... interface StringStack{
void push(String s); String pop(); } interface IntegerStack{ void push(Integer s); Integer pop(); interface StudentStack{...

5 Sort Method static void sort(Integer[] array) { // ... }
static void sort(Double[] array) { static void sort(String[] array) { static void sort(Student[] array){

6 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

7 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 We need some type check just for compile time(for humans not computers)

8 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)

9 Generic stack Stack<Havij> stack=new Stack<Havij>();
Stack.push(new Havij()); Stack<Golabi> stack=new Stack<Golabi>(); Stack.push(new Golabi());

10 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!!

11 Generic classes

12 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();

13 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];

14 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

15 Compile-time Type Checking
Stack<String> stack1 = new Stack<String>(); stack1.push(new Integer(2)); Compile-time error

16 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];

17 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

18 Generic methods

19 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

20 printArray() Generic Method

21 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?

22 You can specify generic type for methods too.

23 Type erasure

24 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”));

25 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

26 Erasure Example (1) class Stack<T>{ void push(T s){...}
T pop() {...} } Is translated to class Stack { void push(Object s){...} Object pop() {...}

27 Erasure Example (2) Translated to

28 What Happens if…

29 Some Notes We can also create generic interfaces
interface Stack<T>{ void push(T s); T pop(); }

30 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

31 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");

32 Inheritance and generics

33 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

34 Why? So there is no inheritance relationship between type arguments of a generic class in assignment

35 This works Inheritance relationship between generic classes themselves still exists

36 Still works Entries in a collection maintain inheritance relationship

37 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

38 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);

39 Generics and Wild card

40 Why Wildcards? Problem Consider the problem of writing a routine that prints out all the elements in a collection What is wrong with this?

41 Why Wildcards? Solution
Use Wildcard type argument <?> Collection<?> means Collection of unknown type

42 Bounded wild character
If you want to bound the unknown type to be a subtype of another type, use bounded Wildcard

43 Restrictions on generic types

44 Not primitive type Cannot Instantiate Generic Types with Primitive Types

45 Not insatiate Cannot Create Instances of Type Parameters

46 Not static Cannot Declare Static Fields Whose Types are Type Parameters Confusing code:

47 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>.

48 Arrays of Parameterized Types
You cannot create arrays of parameterized type

49 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<>();

50 end


Download ppt "Generic(Parameterized ) Types"

Similar presentations


Ads by Google