Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.

Similar presentations


Presentation on theme: "Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1."— Presentation transcript:

1 Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1

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

3 3 Why generics

4 4

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

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

7 7 The Problem What is wrong with these examples? Code redundancy No effective code reuse Solution? Using Object class Pros and Cons? Compile-time type safety

8 8 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) Compile time vs runtime time

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

10 10 Generic stack Stack stack=new Stack (); Stack.push(new Havij()); Stack stack=new Stack (); Stack.push(new Golabi());

11 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 12 Generic classes

13 13 Type parameter as the Return Type interface Stack { void push(T s); T pop(); } Stack stringStack = new... stringStack.push(“salam”); String s = stringStack.pop();

14 14 public class Stack { 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]; }

15 15 Using Stack Class Stack stack1 = new Stack (); stack1.push("first"); stack1.push("second"); System.out.println(stack1.pop()); Stack stack2 = new Stack (); stack2.push(1); stack2.push(2); System.out.println(stack2.pop());

16 16 Compile-time Type Checking Stack stack1 = new Stack (); stack1.push(new Integer(2)); Compile-time error

17 17 public class Stack { 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]; }

18 18 Generic methods

19 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 20 printArray() Generic Method

21 21 Benefits of Generics public static void printArray( E[] inputArray ){…} Restricting possible types Compile-time type checking printArray(stringArray) brings Compiler Error or exception?

22 22 You can specify generic type for methods too.

23 23 Type erasure

24 24 Raw Types Generic classes and methods can be used without type parameter Stack s = new Stack (); String as type parameter s.push(“salam”); s.push(new Integer(12));  Compiler Error Stack objectStack = new Stack(); no type parameter s.push(“salam”); s.push(new Integer(12)); s.push(new Student(“Ali Alavi”));

25 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 26 Erasure When the compiler translates generic method into Java bytecodes It removes the type parameter section It replaces the type parameters with actual types. This process is known as erasure

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

28 28 Erasure Example (2) Translated to

29 29 What Happens if…

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

31 31 What Happens if… public static 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 32 Multiple Type Parameters class MultipleType { private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } public void doSomthing(K k, T t){…} } MultipleType multiple = new MultipleType (); multiple.doSomthing(5, "123");

33 33 Inheritance and generics

34 34 Generics and subtypes You can 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 ao = new ArrayList (); This is counter-intuitive at the first glance

35 35 Why? So there is no inheritance relationship between type arguments of a generic class

36 36 This works Inheritance relationship between generic classes themselves still exists

37 37 Still works Entries in a collection maintain inheritance relationship

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

39 39 class GenericList extends Object{ public void add(T t){...} public T get(int i) {...} public void remove(int i) {...} } class GenericNumericList extends GenericList { } class NonZeroIntegerList extends GenericList { public void add(Integer t) { if(t==null || t==0) throw new RuntimeException(“Bad value"); super.add(t); }

40 40 Generics and Wild card

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

42 42 Why Wildcards? Solution Use Wildcard type argument Collection means Collection of unknown type

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

44 44 Restrictions on generic types

45 45 Not primitive type Cannot Instantiate Generic Types with Primitive Types

46 46 Not insatiate Cannot Create Instances of Type Parameters

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

48 48 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 and an ArrayList.

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

50 50 Generics and Java 7 Older versions: ArrayList list = new ArrayList (); With Java 7: ArrayList list = new ArrayList<>(); Type information after new are ignored. List >> list = new ArrayList<>();

51 51 end


Download ppt "Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1."

Similar presentations


Ads by Google