1 CS3240 - Generics L. Grewe 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of.

Slides:



Advertisements
Similar presentations
Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Generic programming in Java
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
UMBC 1 Static and Dynamic Behavior CMSC 432 Shon Vick.
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.
CS180 Generics and Type Safety Dynamic Data Structures 3/21/08.
1 Generics, Type Safety, and Dynamic Data Structures.
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
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 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.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Abstract Classes and Interfaces
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.
©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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
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.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
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.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Genericity Ranga Rodrigo Based on Mark Priestley's Lectures.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Introduction to Generics
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.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Java Generics – Wildcards By: Anupam Chanda. 2 Generics and Subtyping We start to run into some new issues when we do some things that seem “normal”.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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:
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
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.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Generics Dr. Clincy - Lecture.
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generic programming in Java
Comp 212: Intermediate Programming Lecture 18 – Java Generics
CMSC 202 Generics.
Java Programming Language
Review: libraries and packages
Chapter 19 Generics.
Presentation transcript:

1 CS Generics L. Grewe

2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of data; instead, they operate over a homogeneous set, where the set type is defined at declaration. Data Structures that contain data (such as lists) are not defined to operate over a specific type of data; instead, they operate over a homogeneous set, where the set type is defined at declaration. Helps with Reusability (no longer need multiple data structures to hold different types of data) Helps with Reusability (no longer need multiple data structures to hold different types of data) Helps control run-time errors if you instead could have data structures containing different (heterogeneous) kinds of data. Helps control run-time errors if you instead could have data structures containing different (heterogeneous) kinds of data.

3 Concept in other languages e.g. C++ e.g. C++ In C++, would write generic stack class using templates template class Stack { private: t data; Stack * next; public: void push (t* x) { … } t* pop ( ) { … } t* pop ( ) { … }};

4 Java Generic Programming Java has class Object Java has class Object Supertype of all object typesSupertype of all object types This allows “subtype polymorphism”This allows “subtype polymorphism” Can apply operation on class T to any subclass S <: T Can apply operation on class T to any subclass S <: T Java 1.0 – 1.4 did not have generics Java 1.0 – 1.4 did not have generics No parametric polymorphismNo parametric polymorphism Many considered this the biggest deficiency of JavaMany considered this the biggest deficiency of Java Java type system does not let you “cheat” Java type system does not let you “cheat” Can cast from supertype to subtypeCan cast from supertype to subtype Cast is checked at run timeCast is checked at run time

5 Run-Time Error without Generics Example from sun.java.com: In the first example (lines 13 to 20), you might believe you're working with a list of Integer objects, when in reality it's a list of Strings. In the second example (lines 11 and 22 to 27), you might think you're working with a homogenous set of String, but this is a heterogeneous set of both String and Integer elements. So unless you create a new list subclass for every element type (which would undermine the advantages of OO reuse), there's no way to statically constrain the list to a set of homogeneous elements. And in this simple example, the errors are fairly easy to catch. In a bigger program, you'd have even bigger problems. Example from sun.java.com: In the first example (lines 13 to 20), you might believe you're working with a list of Integer objects, when in reality it's a list of Strings. In the second example (lines 11 and 22 to 27), you might think you're working with a homogenous set of String, but this is a heterogeneous set of both String and Integer elements. So unless you create a new list subclass for every element type (which would undermine the advantages of OO reuse), there's no way to statically constrain the list to a set of homogeneous elements. And in this simple example, the errors are fairly easy to catch. In a bigger program, you'd have even bigger problems List stringList = new LinkedList(); 3. List integerList = new LinkedList(); integerList.add(new Integer(1)); 6. integerList.add(new Integer(2)); stringList.add(new String("I am a String")); // Nothing constrains the elements to a homogeneous set. 11. stringList.add(new Integer(1)); Iterator listIterator = integerList.iterator(); // Compiler unaware of the list's return type and the illegal cast. 16. // Developer meant to iterate through the string list. 17. while(listIterator.hasNext()) { // Illegal cast caught at runtime. 20. String item = (String)listIterator.next(); 21. } listIterator = stringList.iterator(); 24. // No guarantee of homogeneous containers. 25. while (listIterator.hasNext()) { 26. // fail at runtime due to heterogeneous set 27. String item = (String)listIterator.next(); 28. } List stringList = new LinkedList(); 3. List integerList = new LinkedList(); integerList.add(new Integer(1)); 6. integerList.add(new Integer(2)); stringList.add(new String("I am a String")); // Nothing constrains the elements to a homogeneous set. 11. stringList.add(new Integer(1)); Iterator listIterator = integerList.iterator(); // Compiler unaware of the list's return type and the illegal cast. 16. // Developer meant to iterate through the string list. 17. while(listIterator.hasNext()) { // Illegal cast caught at runtime. 20. String item = (String)listIterator.next(); 21. } listIterator = stringList.iterator(); 24. // No guarantee of homogeneous containers. 25. while (listIterator.hasNext()) { 26. // fail at runtime due to heterogeneous set 27. String item = (String)listIterator.next(); 28. } 29.

6 Can generics help this problem With generics, you achieve polymorphic behavior similar to the previous code, but with strong static type-checking; the compiler knows that the two lists are different because they contain different elements, and these lists are guaranteed to contain only a homogeneous set of elements. With generics, you achieve polymorphic behavior similar to the previous code, but with strong static type-checking; the compiler knows that the two lists are different because they contain different elements, and these lists are guaranteed to contain only a homogeneous set of elements.

7 Previous Example with Generics As you can see from comments in the code, all the errors are caught at compile time. Don't worry about the syntax for now -- we'll cover that shortly. As you can see from comments in the code, all the errors are caught at compile time. Don't worry about the syntax for now -- we'll cover that shortly. In comparing the two examples, you should notice that additional type information is included in the generics code, which directs the compiler as to what type each container should contain import java.util.LinkedList; 3. import java.util.Collections; 4. import java.util.Iterator; public class genericsExample2{ static public void main(String[] args) { 9. LinkedList stringList = new LinkedList (); 10. LinkedList integerList = new LinkedList (); integerList.add(new Integer(1)); 13. integerList.add(new Integer(2)); stringList.add(new String("I am a String")); 16. stringList.add(new Integer(1)); // causes a compilation error In comparing the two examples, you should notice that additional type information is included in the generics code, which directs the compiler as to what type each container should contain import java.util.LinkedList; 3. import java.util.Collections; 4. import java.util.Iterator; public class genericsExample2{ static public void main(String[] args) { 9. LinkedList stringList = new LinkedList (); 10. LinkedList integerList = new LinkedList (); integerList.add(new Integer(1)); 13. integerList.add(new Integer(2)); stringList.add(new String("I am a String")); 16. stringList.add(new Integer(1)); // causes a compilation error

8 /* genericsExample2.java:16: cannot resolve symbol 19. ** symbol : method add (java.lang.Integer) 20. */ Iterator listIterator = integerList.iterator(); 23. String item; 24. while(listIterator.hasNext()) { 25. item = listIterator.next(); // causes a compilation error /* genericsExample2.java:25: incompatible types 28. ** found : java.lang.Integer 29. ** required: java.lang.String 30. */ 31. } listIterator = stringList.iterator(); // causes a compilation error /* genericsExample2.java:33: incompatible types 36. ** found : java.util.Iterator 37. ** required: java.util.Iterator 38. */ 39. // the iterator is guaranteed to be homogeneous 40. while (listIterator.hasNext()) { 41. item = listIterator.next(); /* genericsEx2.java:41: incompatible types 44. ** found : java.lang.Integer 45. ** required: java.lang.String 46. */ 47. } 48. } // main 49. } // class genericsExample2 /* genericsExample2.java:16: cannot resolve symbol 19. ** symbol : method add (java.lang.Integer) 20. */ Iterator listIterator = integerList.iterator(); 23. String item; 24. while(listIterator.hasNext()) { 25. item = listIterator.next(); // causes a compilation error /* genericsExample2.java:25: incompatible types 28. ** found : java.lang.Integer 29. ** required: java.lang.String 30. */ 31. } listIterator = stringList.iterator(); // causes a compilation error /* genericsExample2.java:33: incompatible types 36. ** found : java.util.Iterator 37. ** required: java.util.Iterator 38. */ 39. // the iterator is guaranteed to be homogeneous 40. while (listIterator.hasNext()) { 41. item = listIterator.next(); /* genericsEx2.java:41: incompatible types 44. ** found : java.lang.Integer 45. ** required: java.lang.String 46. */ 47. } 48. } // main 49. } // class genericsExample2

9 public class OldBox { Object data; public OldBox(Object data) { this.data = data; } public Object getData() { return data; } OldBox intBox = new OldBox(42); int x = (Integer) intBox.getData(); OldBox strBox = new OldBox(“Hi”); String s = (String) strBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; ClassCastException! Compiles but fails at runtime ANOTHER Example of Problem without Generics: Cast Exceptions at Runtime

10 public class IntBox { Integer data; public IntBox(Integer data) { this.data = data; } public Integer getData() { return data; } public class StrBox { String data; public StrBox(String data) { this.data = data; } public String getData() { return data; } IntBox intBox = new IntBox(42); int x = intBox.getData(); StrBox strBox = new StrBox(“Hi”); String s = strBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; Errors caught by compiler public class FooBox { Foo data; public FooBox(Foo data) { this.data = data; } public Foo getData() { return data; } Infinite many classes possible Without Generics - NOT A GOOD SOLUTION

11 Java Generics: Key Idea Parameterize type definitions Parameterize type definitions Parameterized classes and methodsParameterized classes and methods Provide type safety Provide type safety Compiler performs type checkingCompiler performs type checking Prevent runtime cast errorsPrevent runtime cast errors

12 Generics: Parameterized Classes public class OldBox { Object data; public OldBox(Object data) { this.data = data; } public Object getData() { return data; } We want the box to hold a “specific” class – abstractly represented Object does not work as we have seen earlier Solution – parameterize the class definition public class Box { E data; public Box(E data) { this.data = data; } public E getData() { return data; } E refers to a particular type The constructor takes an object of type E, not any object To use this class, E must be replaced with a specific class USING Generics

13 How to Use Parameterized Classes public class Box { E data; public Box(E data) { this.data = data; } public E getData() { return data; } Box intBox = new Box (42); int x = intBox.getData();//no cast needed Box strBox = new Box (“Hi”); String s = strBox.getData();//no cast needed Following lines will not compile anymore: String s = (String) intBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; Runtime errors now converted to compile time errors

14 When to Use Parameterized Classes Particularly useful for “container” classes Particularly useful for “container” classes Containers hold but do not process dataContainers hold but do not process data All collections framework classes in Java 5.0 and on defined using generics All collections framework classes in Java 5.0 and on defined using generics See the Java API documentationSee the Java API documentation

15 Collections now use Generic (see java.util) Generic interface Generic interface Generic class implementing Collection interface Generic class implementing Collection interface class LinkedList implements Collection { protected class Node { protected class Node { A elt; A elt; Node next = null; Node next = null; Node (A elt) { this.elt = elt; } Node (A elt) { this.elt = elt; } }......} interface Iterator { E next(); boolean hasNext(); } interface Collection { public void add (A x); public Iterator iterator (); }

16 More Collections Code from java.util public interface List { void add(E x); public interface List { void add(E x); Iterator iterator(); Iterator iterator(); } public interface Iterator { E next(); E next(); boolean hasNext(); boolean hasNext();} LinkedList is in java.util and implements List interface as a Generic Class. HOW TO USE THIS CODE List myIntList = new LinkedList (); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();

17 Parameterized Classes: Syntax Note A class can have multiple parameters, e.g: public class Stuff { … } Subclassing parameterized classes allowed, e.g: /* Extending a particular type */ class IntBox extends Box { … } Or /* Extending a parameterized type */ class SpecialBox extends Box { … } SpecialBox is a subclass of Box. /* Following assignment is legal */ Box sb = new SpecialBox (“Hi”);

18 Parameterized Classes in Methods A parameterized class is a type just like any other class. It can be used in method input types and return types, e.g: Box aMethod(int i, Box b) { … } If a class is parameterized, that type parameter can be used for any type declaration in that class, e.g: public class Box { E data; public Box(E data) { this.data = data; } public E getData() { return data; } public void copyFrom(Box b) { this.data = b.getData(); } }//We have added an infinite number of types of Boxes //by writing a single class definition

19 So Far… Type safety violations Type safety violations Using castsUsing casts Parameterized classes solve this problem Parameterized classes solve this problem Provide type safety Provide type safety Enforced by the compilerEnforced by the compiler Particularly useful for container classes Particularly useful for container classes A parameterized class is another type A parameterized class is another type Next – bounded parameterized classes Next – bounded parameterized classes

20 Bounded Parameterized Types Sometimes we want restricted parameterization of classes. We want a box, called MathBox that holds only Number objects. We can’t use Box because E could be anything. We want E to be a subclass of Number. public class MathBox extends Box { public MathBox(E data) { super(data); } public double sqrt() { return Math.sqrt(getData().doubleValue()); }

21 Bounded Parameterized Types (Contd.) public class MathBox extends Box { public MathBox(E data) { super(data); } public double sqrt() { return Math.sqrt(getData().doubleValue()); } The syntax means that the type parameter of MathBox must be a subclass of the Number class. We say that the type parameter is bounded. new MathBox (5);//Legal new MathBox (32.1);//Legal new MathBox (“No good!”);//Illegal

22 Bounded Parameterized Types (Contd.) Inside a parameterized class, the type parameter serves as a valid type. So the following is valid. public class OuterClass { private class InnerClass { … } … } Syntax note: The syntax is valid even if B is an interface.

23 Bounded Parameterized Types (Contd.) Java allows multiple inheritance in the form of implementing multiple interfaces. So multiple bounds may be necessary to specify a type parameter. The following syntax is used then: For instance: interface A { … } interface B { … } class MultiBounds { … }

24 Parameterized Methods public class Bar { //Bar is parameterized public T aMethod(T x) { return x; } public static void main(String[] args) { Bar bar = new Bar (); int k = bar.aMethod(5); String s = bar.aMethod("abc"); //Compilation error here } Once Bar object is fixed, we are locked to a specific T.

25 Use of Parameterized Methods Adding type safety to methods that operate on different types Adding type safety to methods that operate on different types Return type dependent on input typeReturn type dependent on input type

26 Upper Bounded Wildcards in Parameterized Types The following is a PROBLME: Box numBox = new Box (31); Compiler comes back with an “Incompatible Type” error message. This is because numBox can hold only a Number object and nothing else, not even an object of type Integer which is a subclass of Number. The type of numBox we desire is “a Box of any type which extends Number ”. Box numBox = new Box (31); SOLUTION

27 Upper Bounded Wildcards in Parameterized Types (Contd.) public class Box { public void copyFrom(Box b) { this.data = b.getData(); } //We have seen this earlier //We can rewrite copyFrom() so that it can take a box //that contains data that is a subclass of E and //store it to a Box object public class Box { public void copyFrom(Box b) { this.data = b.getData();//b.getData() is a //subclass of this.data } is called “upper bounded wildcard” because it defines a type that is bounded by the superclass E.

28 Lower Bounded Wildcards in Parameterized Types Suppose we want to write copyTo() that copies data in the opposite direction of copyFrom(). copyTo() copies data from the host object to the given object. This can be done as: public void copyTo(Box b) { b.data = this.getData(); } Above code is fine as long as b and the host are boxes of exactly same type. But b could be a box of an object that is a superclass of E. This can be expressed as: public void copyTo(Box b) { b.data = this.getData(); //b.data() is a superclass of this.data() } is called a “lower bounded wildcard” because it defines a type that is bounded by the subclass E.

29 Unbounded Wildcards Use unbounded wildcards when any type parameter works. is used to specify unbounded wildcards. The following are legal statements. Box b1 = new Box (31); Box b2 = new Box (“Hi”); b1 = b2; Wildcard capture: The compiler can figure out exactly what type b1 is above from the right hand side of the assignments. This “capturing” of type information means: 1. The type on the left hand doesn’t need to be specified. 2. The compiler can do additional type checks because it knows the type of b1.

30 Conclusion Java generics Java generics Parameterized classes and methodsParameterized classes and methods Type safetyType safety Syntax and semantics through examplesSyntax and semantics through examples