Www.javacup.ir Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

Sadegh Aliakbary Sharif University of Technology Spring 2011.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Java Generics.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
 2006 Pearson Education, Inc. All rights reserved Generics.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Chapter 3 Introduction to Collections – Stacks Modified
Java Generics.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
 2005 Pearson Education, Inc. All rights reserved Generics.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Types in programming languages1 What are types, and why do we need them?
CIS 270—Application Development II Chapter 18-Generics.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Peyman Dodangeh Sharif University of Technology Spring 2014.
CMSC 330: Organization of Programming Languages Java Generics.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Generic(Parameterized ) Types
Chapter 20 Generic Classes and Methods
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Generic programming in Java
Generics, Lambdas, Reflections
Generic Classes and Methods
Presentation transcript:

Sadegh Aliakbary

Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP is clearly noted as the source in the used case. JAVACUP shall not be liable for any errors in the content, or for any actions taken in reliance thereon. Please send your feedback to 2JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Agenda Generic Methods Generic Classes Generics and Inheritance Erasure JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source3

JAVACUP.ir4

Stack interfaces interface StringStack{ void push(String s); String pop(); } interface IntegerStack{ void push(Integer s); Integer pop(); } interface StudentStack{... JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source5

Sort Method static void sort(Integer[] array) { //... } static void sort(Double[] array) { //... } static void sort(String[] array) { //... } static void sort(Student[] array){ //... } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source6

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 JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source7

The Solution Generic types and methods Methods with similar implementation Applicable for different parameters JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source8

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 JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source9 Type Parameter It says: In this method, E is not a regular type, it is a generic one

printArray() Generic Method 10

Benefits of Generics public static void printArray( E[] inputArray ){…} Restricting possible types Compile-time type checking printArray(stringArray) brings Compiler Error or exception? JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source11

Type parameter as the Return Type JAVACUP.ir12

Stack Generic Interface interface Stack { void push(T s); T pop(); } Stack stringStack = new... stringStack.push(“salam”); String s = stringStack.pop(); JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source13

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 = (E[]) new Object[size]; } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source14 A note, later….

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()); JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source15

Compile-time Type Checking Stack stack1 = new Stack (); stack1.push(new Integer(2)); Compile-time error JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source16

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 = (E[]) new Student[size]; } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source17 A note, later….

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”)); JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source18

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 erasure JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source19

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 JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source20

Erasure Example (1) class Stack { void push(T s){...} T pop() {...} } Is translated to class Stack { void push(Object s){...} Object pop() {...} } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source21

Erasure Example (2) Translated to JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source22

What Happens if… public static void f(E i){ } public static void f(Number i){ } Compiler Error : Method f(Number) has the same erasure f(Number) as another method in this type JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source23

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 JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source24

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); } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source25

Some Notes We can also create generic interfaces interface Stack { void push(T s); T pop(); } No primitives as type parameters JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source26

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"); JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source27

Note You can not instantiate generic classes class Stack { T ref = new T(); } Syntax Error: Cannot instantiate the type T Why? JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source28

Note (2) You can not instantiate generic classes class Stack { T[] elements = new T[size]; } Syntax Error: Cannot instantiate the type T Why? JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source29

Note (3) You cannot create a generic array class Box { final T x; Box(T x) { this.x = x; } } Then, this line brings a compile error: Box [] bsa = new Box [3]; Why? JAVACUP.ir30 Syntax Error: Cannot create a generic array of Box Syntax Error: Cannot create a generic array of Box

Reason Operations such as instanceof and new are runtime operations They use a type at runtime With erasure type information is removed at runtime So these operations are Meaningless Although, they may be possible JAVACUP.ir31 T ref = new T();  impossible which constructor? T[] elements = new T[size ];  Meaningless Box [] bsa = new Box [3];  Meaningless

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<>(); JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source32

Further Reading Wildcards as type parameters Java generics vs. C++ templates Erasure is different in these languages Type Argument inference More on erasure TIJ is so better than Deitel in generics chapter More Depth JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source33

Wow!!! public static void wow(ArrayList list) { Method method = list.getClass().getMethod("add", Object.class); method.invoke(list, new Integer(2)); } public static void main(String args[]) { ArrayList s = new ArrayList (); wow(s); for (Object string : s) { System.out.println(string); } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source34

A Note on Inheritance class A{ public Object f(Object o){ return new Object(); } class B extends A{ public Object f(Object o){ return new String("salam"); } B.f() overrides A.f() JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source35

A Note on Inheritance class A{ public Object f(Object o){ return new Object(); } class B extends A{ public String f(Object o){ return new String("salam"); } B.f() overrides A.f() JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source36

A Note on Inheritance class A{ public Object f(Object o){ return new Object(); } } class B extends A{ public Object f(String o){ return new String("salam"); } } B.f() is overloading A.f() B.f() does not override A.f() JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source37

Pair class (Quiz) Pair equals toString JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source38

class Pair { private T first; private K second; public Pair(T t, K k) { this.first = t; this.second = k; } public T getFirst() { return first; } public K getSecond() { return second; } public String toString() { return "[" + second + ", " + first + "]"; } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source39

Pair pair1 = new Pair (4, "Ali"); Integer i = pair1.getFirst(); String s = pair1.getSecond(); Pair pair2 = new Pair ("salam", true); String ss = pair2.getFirst(); Boolean bb = pair2.getSecond(); JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source40

equals() method public boolean equals(Pair pair) { return pair.first.equals(first) && pair.second.equals(second); } What is wrong with this implementation? JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source41

boolean equals(Pair pair) It should check for nullity of pair It should check for nullity of pair.first and pair.second It should check for nullity of this.first and this.second This method does not override equals() It is overloading it Correct signature: boolean equals(Object pair) What if parameter is not a Pair? JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source42

Type Checking public boolean equals(Object o) { Pair pair = null; try{ pair = (Pair ) o; }catch(ClassCastException e){ return false; } return pair.first.equals(first) && pair.second.equals(second); } JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source43

JAVACUP.ir44

JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source45