Generics OOP Tirgul 8 2006. What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)

Slides:



Advertisements
Similar presentations
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
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.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Java Generics.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) 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.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
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.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
1 Genericity Parameterizing by Type. 2 Generic Class One that is parameterized by type  Works when feature semantics is common to a set of types On object.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
Ics202 Data Structures. U n i v e r s i t y o f H a i l 1. Stacks top push (8)push (2)
Chapter 3 Introduction to Collections – Stacks Modified
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CS 2430 Day 26. Announcements Exam #2: Wednesday, April 3 –Review in lab on Tuesday, April 2 –Sample problems sent via .
Effective Java: Generics Last Updated: Spring 2009.
 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 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Consider the following Which of the following will cause a java.lang.ClassCastException? a)Alpha a = x; b)Foo f= (Delta)x; c)Foo f= (Alpha)x; d)Beta b.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ADSA: Generics/ Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Generics CompSci 230 S Software Construction.
Object-Oriented Programming Simple Stack Implementation.
CIS 270—Application Development II Chapter 18-Generics.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Stacks Nour El-Kadri CSI Stacks Software stacks are abstract data types (structures) similar to physical stacks, Plates Trays Books PEZ dispenser.
CMSC 330: Organization of Programming Languages Java Generics.
Java 1.5 Generics Amr Ali Software Engineer, IBM-Egypt EG-JUG.
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.
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
CS 2430 Day 24. Announcements Quiz this Friday Program 5 posted on Monday Program 4 due date: Friday at 10pm Program 4 grace date: Wednesday at 10pm (don’t.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
1. Last Lecture Stacks and Queues implemented with a Linked List Doubly Linked Lists 2 Today.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
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.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
CIS265/506 Cleveland State University – Prof. Victor Matos
Generic(Parameterized ) Types
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Stacks and Queues.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
COMPUTER 2430 Object Oriented Programming and Data Structures I
class PrintOnetoTen { public static void main(String args[]) {
Chapter 19 Generics.
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Presentation transcript:

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) myStack.pop()).intValue() ; // annoying cast Stack myStack = new Stack () ; myStack.push(new Integer(0)) ; int x = myStack.pop().intValue() ; // no cast is needed Using generics, the code looks like this: Without Using generics, the code looks like this: More readable and more typesafe!

Implementation Issues Defining a Generic Stack public interface Stack { public boolean empty() ; public E peek() ; public E pop() ; public E push (E item) ; public E peek() ; } Using a single letter in UPPER CASE for the type is the acceptable naming convention

Implementation Issues Generics and inheritance Stack objectStack = new Stack () ; Stack integerStack=objectStack ; // illegal assignment Although Integer Inherits Object, Stack is a different type from Stack

Remark Stack objectStack = new Stack () ; Stack myStack = objectStack ; // is this legal ? (compile // time warning) Integer x = new Integer(0); myStack.push(x) ; // what happens here? (Runtime error)

Implementation Issues Generics and inheritance(2) public void printAndEmptyStack(Stack stack) { while (!stack.empty()) System.out.println(stack.pop()); } What is the problem when using generics ? How do we implement it using generics ?

Implementation Issues Generics and inheritance(3) Using wildcards : public void printAndEmptyStack( Stack stack) { while (!stack.empty()) System.out.println(stack.pop()); } Stack is a called “stack of unknowns”.

Implementation Issues Generics and inheritance(4) Anima l HorseZebraFrog

Implementation Issues Generics and inheritance(5) Assume we want to print and empty only stacks of animals, i.e Stack, Stack etc. The correct syntax is : public void printAndEmptyStack ( Stack stack) { while (!stack.empty()) System.out.println(stack.pop()); } Note: Stack given to this function is a legal type.

Implementation Issues Generics and inheritance(6) Is this code legal ? public void addElement ( Stack s) { s.add (new Frog() ) ; } What if the parameter given to the method was Stack ?

Generic Methods Version 1: public static void insertElementToStack (Object element, Stack c) { if (element != null) c.push(element) ; //compile time error } Version 2 : public static void insertElementToStack (? element, Stack c) { if (element != null) c.push(element) ; } // compile time error – no such type “?”

Generic Methods(2) Version 3: public static void insertElementToStack (T element, Stack c) { if (element != null) c.push(element) ; } // this version is the way to do it

Generic Methods(3) public static void insertElementToStack (E element, Stack c) { if (element != null) c.push(element) ; } // this allows inserting elements which inherit from a base // class

Arrays public class Stack { private final static int INITIAL_CAPACITY = 100 ; private E[] _stack = new E[INITIAL_CAPACITY]; // compile time // error }

Exercises Is the following legal : public static void add (String s, Stack stack) { stack.push(s) ; } public static void main(string args[] ) { Stack s = new Stack (); add( “hapoel”, s) ; }

Exercises(2) Is the following legal : public static void add (String s, Stack stack) { stack.push(s) ; } public static void main(string args[] ) { Stack s = new Stack () ; add( “hapoel”, s) ; }

Exercises(3) Is the following legal : public static void addNull( Stack stack) { stack.push( null ) ; } public static void main(string args[] ) { Stack s = new Stack (); addNull(s) ; }