Generic(Parameterized ) Types

Slides:



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

Sadegh Aliakbary Sharif University of Technology Fall 2012.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Generic programming in Java
Java Generics.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
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 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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
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.
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.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
 2005 Pearson Education, Inc. All rights reserved Generics.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Introduction to Generics
Peyman Dodangeh Sharif University of Technology Spring 2014.
CMSC 330: Organization of Programming Languages Java Generics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
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:
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
(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.
Java Generics And collections
Modern Programming Tools And Techniques-I
Generics, Exceptions and Undo Command
CIS265/506 Cleveland State University – Prof. Victor Matos
More on Java Generics Multiple Generic Types Bounded Generic Types
Chapter 20 Generic Classes and Methods
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Generics, Lambdas, Reflections
Interfaces and Inheritance
Generics.
Advanced Programming Behnam Hatami Fall 2017.
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Advanced Programming in Java
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
CMSC 202 Generics.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
slides created by Alyssa Harding
Generics, Stack, Queue Based on slides by Alyssa Harding
Generic Programming.
Generics 5/11/2019.
Chapter 21 Generics.
Chapter 19 Generics.
CMPE212 – Reminders Assignment 2 due next Friday.
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Generic Classes and Methods
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Chapter 19 Generics.
Presentation transcript:

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