Generics. Type parameters The definition of “ArrayApplier” in applier.java and applier2.java allows any function from int to int. But suppose you want.

Slides:



Advertisements
Similar presentations
New features in JDK 1.5 Can these new and complex features simplify Java development?
Advertisements

Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
Programming Languages and Paradigms
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Generic programming in Java
CSSE221: Software Dev. Honors Day 12 Announcements Announcements No baby yet… No baby yet… Fifteen done. Fifteen done. Please read Class Announcements.
Java Generics.
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Modules and Object-Oriented Programming. Modules (Packages) Programming in the Large Information hiding Limit the ways in which one part of the program.
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.
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Generic Programming Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 The Problem Assume we have a nice Stack implementation. Our stack receives.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
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.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
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.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java Generics.
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.
Adapted from Prof. Necula UCB CS 1641 Overview of COOL ICOM 4029 Lecture 2 ICOM 4029 Fall 2008.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
Names and Scope. Scope Suppose that a name is used many times for different entities in text of the program, or in the course of execution. When the name.
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.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
Types in programming languages1 What are types, and why do we need them?
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
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.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
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:
Object Oriented Programming in Java Lecture 14. Review Quiz 1. Write a method which gets an Object and call all its available ‘get’ Methods and print.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
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.
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 Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Sixth Lecture ArrayList Abstract Class and Interface
Generic Programming David Rabinowitz.
Introducing Java Generics and Collections
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 21 Generics.
Subtype Substitution Principle
Chapter 19 Generics.
Presentation transcript:

Generics

Type parameters The definition of “ArrayApplier” in applier.java and applier2.java allows any function from int to int. But suppose you want to write a single array applier for any function from type T1 to T2? Dynamic method binding allows the type of “self” to be variable, but there’s no way to get 2 variable types.

Generics in Ada Essentially a structured macro. generic type Item is private; type ItemArray is array (Integer range <>) of Item; with function f(X: Item) return Item; procedure ArrayApplier(A,B: in out ItemArray) begin for I in 1.. A’Last loop B[I] = f(A[I]); end loop end

Instantiating an Ada generic function incr(I: Integer) return Integer is begin return I+1; end; type IntArray is array(Integer range<>) of Integer; function ApplyIncr is new ArrayApplier(Integer,IntArray,incr);

Implementation Each instantiation of the generic is built by a preprocessor at compile time, and compiles to a separate routine. Like a macro.

C++ templates template int compare(const T &v1, const T &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } int I,J; compare(I,J); // int compare double X,Y; compare(X,Y); // double compare compare(I,X); // compiler error

Java generics: example interface UnaryFun { public S f(T x); } class IntSqrt implements UnaryFun { public Float f(Integer i) { return new Float(Math.sqrt(i)); }}

Example continued class Applier { public void ApplyToArray( UnaryFun Q, T[] A, S[] B) { for (int i=0; i < A.length; i++) B[i] = Q.f(A[i]); }}

Example continued … main … Integer A[] = new Integer[] {1,2,3}; Integer C[] = new Integer[3]; IntSqrt ISQ = new IntSqrt(); Applier IFApp = new Applier (); IFApp.ApplyToArray(ISQ,A,C);

Generic types LinkedList list = new LinkedList(); list.add(new Integer(1)); Integer num = (Integer) list.get(0); LinkedList L = new LinkedList (); L.add(new Integer(1)); Integer num = list.get(0);

Subtypes of generic types LinkedList LI = new LinkedList (); LinkedList LO = LI; // Type error! LO.add(new String(“Hello”)); Difference between extensional and abstraction view of types. Therefore if a method has a parameter of type LinkedList you can’t pass an argument of type LinkedList

Wildcards void printCollection(Collection c) { for (Object e : c) { System.out.println(e);} LinkedList L; printCollection(L);

Restricted type parameters and wildcards, void drawAll(List L) { for (shape S : L) draw(S); } Type definition for max(c) (simplified): public static > T max(Collection coll)

Embedded Type Parametrization LinkedList > static List > history = new ArrayList >; public void drawAll(List shapes) { history.addLast(shapes); for (Shape s: shapes) s.draw(this); }

Implementation: Type erasure No record of the parameter value at run time. If L is of type LinkedList, all the interpreter knows at runtime is that it is of type LinkedList. One subroutine for ApplyToArray, not a separate routine for each different argument type (as in Ada and C++). Possible because parameters are reference types and all the same size.

Bug, not a feature Done for compatibility with legacy code. In complex cases, leads to need for casts, runtime type checking, type unsafe code.

Morals Backward compatibility is the source of much grief. (Forward compatibility is a myth.) It is challenging to develop a type theory of complex entities (collections, functions, etc.) that is both adequate and well-defined.