#Students per correct answers

Size: px
Start display at page:

Download "#Students per correct answers"

Transcription

1 Generics in Java Programming Projects 14/04/15 1 #Students per correct answers Quiz"2" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" #"Correct"Answers" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" 1

2 The collections interfaces Maps unique keys to values Contains unique elements Ordered collection Ordered collection Ordered unique of elements of elements with elements head and tail; 14/04/15 elements are always 3 removed from the head Maps unique keys to values and sort values Collections in Java Array has a special language support Iterators Iterator(I) Collections also called containers Collection(I) Set(I) HashSet(c), TreeSet(c) List(I) ArrayList(c), LinkedList(c) Map(I) HashMap(c), TreeMap(c) 14/04/15 Barbara Russo 2

3 Built-in Java collections Collection interfaces and collection classes Collection classes either full implements the collections interfaces or are abstract classes providing skeleton implementations Examples: AbstractCollection, AbstractList, AbstractSequentialList, AbstractSet, AbstractMap 14/04/15 Barbara Russo Getting from a collection Let us consider this example: List myintegerlist = new LinkedList(); myintegerlist.add(new Integer(0)); Integer x = (Integer) myintegerlist.iterator().next(); The cast on line 3 is slightly annoying Typically, programmer knows what kind of data has been placed into a particular list. However, the cast is essential The compiler can only guarantee that iterator returns an object of type Object 14/04/15 6 3

4 Getting from a collection The casting introduces a run time error, since the programmer might be mistaken What if programmers could mark a list as being of a particular data type? This is the idea behind generics 14/04/15 7 Generics Generics allow you to abstract over types The most common examples are container (e.g., arrays and lists) types, such as those in the Collection hierarchy List<Integer> is a generic type that says that the list is of integers. List<Integer> alist = new List<Integer>(); 14/04/15 8 4

5 Example casting run time with generics compile time List myintegerlist = new LinkedList(); myintegerlist.add(new Integer(0)); Integer x = (Integer) myintegerlist.iterator().next(); List<Integer> myintegerlist = new LinkedList<Integer>(); myintegerlist.add(new Integer(0)); Integer x = myintegerlist.iterator().next(); 14/04/15 9 A big difference increases robustness With generics, the compiler can check the type correctness of the program at compile-time When we say that myintegerlist is declared with type List<Integer>, this tells us something about the variable myintegerlist and the compiler guarantees the type In contrast, the cast tells us something the programmer thinks is true at a single point in the code and it will be checked at run time: 14/04/

6 Generics and derivation List<String> ls = new ArrayList<String>(); //Ok List<Object> lo = ls; // pointing to the object referenced by ls. Compiler error!!!! Why? The trickier part of the question is line 2. is a List of String a List of Object? Most people s instinct is to answer: sure! lo.add(new Object()); // adding a new entry object of type Object is possible as lo is //a reference variable of a List of Object types String s = ls.get(0); // attempts to assign an Object to a String! NO! The object referenced by ls does not hold just strings anymore! We need to have another instrument more flexible, the Wildcards 14/04/15 11 Wildcards as List<Integer> is not a subtype of List<Object> we cannot use some useful practices of the classic Java anymore For example List can have any type of members whereas List<Integer> can only have Integer members Wildcards are used to get back classic behaviours for subtyping 14/04/

7 Example: Collection of unknown Collection<?> The type of collection is unknown Collection<?> acollection = new ArrayList<String>(); acollection is a reference of a Collection of unknown type and points to an object of type ArrayList of String Note that Collection is an interface and ArrayList Implements List which extends Collection 14/04/15 13 Limitation adding With the collection of unknown, we cannot directly add to Collection a specific object: acollection.add(0,new Object()); //rises a compiler error as we do not know of what type is the collection and we can only pass elements that are subtypes of the unknown, since we do not know the unknown type -> we can only pass null, which is subtype of any type 14/04/

8 Gaining - getting There is no compile time error to use get() and make use of the result, instead. We get back an unknown type, but we always know that it will be an object. Thus we can assign the result of get() to a variable of type Object (covariant property the return type can be a subclass of Object) 14/04/15 15 With collection of unknown Populating a list is uncertain getting from a list is certain 14/04/

9 Bounded Wildcards List<? extends Shape> It is a wildcard bounded by Shape This allows to use the Wildcards with all the subtypes of Shape As subtyping for generics is not allowed, bounded Wildcards allow to extend behaviours to children 14/04/15 17 Example public abstract class Shape{ public abstract void draw(canvas c); public class Circle extends Shape{ public abstract void draw(canvas c){ ; public class Rectangle extends Shape{ public abstract void draw(canvas c){ ; public class Canvas{ public void draw(shape s){ s.draw(this); public void drawall(list<shape> alist){ for( ){ alist.draw(this) drawall can be only used with Shape and it cannot be used with any derived class! Then we define public void drawallreally(list<? estends Shape> alist){ for( ){ alist.draw(this) Now we can use lists of any derived type of Shape List<Circle> alistcircle= new List<Circle>(); Canvas.drawAllReally(aListCircle); 14/04/

10 Careful! Again, it is illegal to write directly into a list through the body of a method public void addrectangle(list<? extends Shape> alist){ alist.add(0,new Rectangle()); //compile time error As we do not know the subtypes of Shape and whether the subtype of Shape is a Rectangle (or a parent class of Rectangle) i.e.: Rectangle extends Base and Base extends Shape We need a new instrument: parametrized types and methods 14/04/15 19 Parameterized type A parameterized type is a class public class Map<E> { ; Where E is a parameter (it is known but not defined) In the use of the class, all occurrences of the formal type parameter (E) are replaced by the actual type argument (e.g., Integer). Map<Integer> amap = new amap<integer>(); Map<Integer> stands for a version of Map where E has been uniformly replaced by Integer 14/04/

11 Note: Pseudo polymorphism with Marker Interfaces Parametrisation of a class can be done through the use of empty interfaces called Marker. Makers allow to group classes that want to have the same services. They are empty. Ex: all the classes that implement Cloneable (I) can use (and must override) the clone() method of Object Maker interfaces are not really providing a parameter Parametrized types public interface Map<K, V> { public void put(k key, V value); public V get(k key); a parameterised type can have more than one parameter... Map<String, String> m = new HashMap<String, String>(); where HashMap<String,String> defines an implementation of Map<String,String> 14/04/

12 and methods one or more parameters are inserted after the modifier parameters in method declaration public <T> void add(t t, List<T> alist){ alist.add(t); //correct 14/04/15 23 and methods Finally we can fill a list! public <T> void add(t t, List<T> alist){alist.add(t); //finally we can fill a list or public <T> void add(list<t> alist, List<? Extends T> achildlist){ ; or public <T,S extends T> void add(list<t> alist, List<S> asmalllist){ ; // equivalent to the one above if S extends T or public <T> void add(list<t> alist, List<S extends T> asmalllsit){ ; // equivalent to the one above or public <T> List<T> returnnewlist(list<t> alist){ ; 14/04/

13 Parameterised types with interfaces With pseudo polymorphism; Comparable is an interface java.lang With generics class MySortedList{ private Comparable [] elements; public SortedList (){ elements = new Comparable[size]; public int add(comparable t); public Comparable remove(int index); public int size(); class MySortedList<T implements Comparable>{ private T [] elements; public SortedList (){ elements = new T[size]; public int add(t t); public T remove(int index); public int size(); 14/04/15 25 Parameterised types with interfaces With pseudo polymorphism; public static void main(string [] args){ MySortedList list = new MySortedList(); // adding Integers Integer i = (Integer)list.remove(0); With generics public static void main(string [] args){ class MySortedList<Integer> list = new MySortedList<Integer>(); // adding Integers Integer i = list.remove(0); As I do not know what will be the implementation type of the object at 0, I have to cast in any case. Here I only know that T implements Comparable. Integer is a standard implementation of Comparable 14/04/

14 Inference of types What does it happen when types in parametrised methods are different? The compiler infers types It always infer the most generic 14/04/15 27 Compiler s inference - Example Static <T> fromarraytocollection(t[] a, Collection<T> c){ for(t o : a){ c.add(o); Object[] aco = new Object[100]; Collection<Object> acollectionobject = new ArrayList<Object>(); fromarraytocollection(aco,acollectionobject); //T is inferred to be Object fromarraytocollection(acs,acollectionstring); // T is inferred to be String fromarraytocollection(acs,acollectionobject); // T is inferred to be Object fromarraytocollection(aci,acollectionnumber); // T is inferred to be Number String[] acs = new String[100]; Collection<String> acollectionstring = new ArrayList<String>(); fromarraytocollection(acf,acollectionnumber); // T is inferred to be Number fromarraytocollection(acn,acollectionnumber); Integer[] aci = new Integer[100]; Float[] acf = new Float[100]; Number[] acn = new Number[100]; // T is inferred to be Number fromarraytocollection(acn,acollectionstring); // T compile time error Collection<Number> acollectionnumber = new ArrayList<Number>(); from: The compiler infers from the less specialized type 14

15 Raw type A raw type is the classic type For example Collection is a classic type Collection<V> is the corresponding generic with type V. The raw type of Collection<V> is Collection 14/04/15 29 Type erasure Type Erasure is the phase after Inference of types in which the compiler translates the source into bytecode. Type erasure exists to have compliance with non generics code (legacy code) Consider the example of the parameterized List public interface List<E> { void add(e x); Iterator<E> iterator(); public interface Iterator<E> { E next(); boolean hasnext(); 14/04/

16 Type erasure at erasure the generic type are removed List<Number> becomes List which can contain any type of object The compiler just check the correctness of the types and then save bytecode as in traditional Java compiled code At run time is impossible to deduce the original type 14/04/15 31 Type erasure If a generic type is not parametric like List<Integer> its erasure is the raw type (List) If the generic type is unbounded (like List<E> or List<?>) its erasure will be Object If the generic type is bounded its erasure will be the base (or the implementation of it if the bound is an interface) <K extends V> -> erasure=v or W (implements V) if V interface If the generic type is bounded by a generic then its erasure will be the raw type of the base. <K extends Comparable<V>> -> erasure= implementation of Comparable (as Comparable is an interface) 14/04/

17 Original Code Compiler s Translation 14/04/15 33 Two ways to handle parameterized types Specialization of objects each instance of the parameterized type creates a new representation. List<Integer> and List<Float> are two different representations of List<T> Sharing of objects the code for List<T> is generated by the compiler for one representation and all the instances created refer to this representation Java uses the second approach Some problems with simple types: a generic with simple type is not allowed as they are treated differently by the compiler 14/04/

18 is instance of a parametric type As implication, it makes no sense to ask an instance if it is an instance of a particular invocation of a generic type: Collection<String> cs = new ArrayList<String>(); if (cs instanceof Collection<String>) {... // illegal As Collection<String> is compiled into one single representation, the implementation of Collection 14/04/15 35 Getting an instance of a parametric type and it is also illegal to write (code will not compile) new T(); where T is a parametric type as we do not know the true type of the object and as such we cannot call its constructor 14/04/

19 Getting an instance of a parametric type To get an instance of a parametric type we use the genericization of Class, Class<T>{ T newinstance(); // in Class we had Object newinstance(); and define a method that gets the instance of T through newinstance(), getclass() public final Class<? extends T> getclass() { 14/04/15 37 Getting an instance of a parametric type Another implication of the fact that a generic class is shared among all its instances List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getclass()); It prints true, because all instances of a generic class have the same raw type, regardless of their actual type parameters 14/04/

20 Static generic type class and method A static member cannot be implemented as generics This is because it is shared by all the objects and the objects of a generic type are of unknown type 14/04/15 39 A difference with Template in C++ Generics do not generate a new class for each specialization of the formal parameter A generic type declaration is compiled once for all and turned into a single class file like ordinary class files. There are no multiple copies of the generics in any place In C++ for Templates this is not true 14/04/

21 Example interface MinMax<T extends Comparable<T>> { T min(); T max(); class MyClass<T extends Comparable<T>> implements MinMax<T > { T[] vals; MyClass(T[] o) { vals = o; public T min() { T v = vals[0]; for(int i=1; i < vals.length; i++) if(vals[i].compareto(v) < 0) v = vals[i]; return v; public T max() { T v = vals[0]; for(int i=1; i < vals.length; i++) if(vals[i].compareto(v) > 0) v = vals[i]; return v; public class GenIFDemo { public static void main(string args[]) { Integer inums[] = {3, 6, 2, 8, 6 ; Character chs[] = {'b', 'r', 'p', 'w' ; MyClass<Integer> iob = new MyClass<Integer>(inums); MyClass<Character> cob = new MyClass<Character>(chs); System.out.println("Max value in inums: " + iob.max()); System.out.println("Min value in inums: " + iob.min()); System.out.println("Max value in chs: " + cob.max()); System.out.println("Min value in chs: " + cob.min()); 14/04/15 41 Source code [1] package card; [2] import game.mycard; [3] public interface Play { [4] int STOP = -1; [5] int OK = 1; [6] [7] package card; [8] public abstract class Card implements Play{ [9] protected static int number = 0; [10] public int points; [11] public String color; [12] public Card(int i, String c){ [13] points = i; [14] color = c; [15] [16] 14/04/

22 [17] package game; [18] import card.*; [19] public class MyCard extends card.card{ [20] private String name; [21] private int next; [22] private int num = 0; [23] public MyCard(int p, String c){ [24] super(p, c); [25] number++; [26] [27] [28] package game; [29] import card.card; [30] public class Game { [31] private int players; [32] private int drinks; [33] private MyCard mycard; [34] public Game(int z, int y){ [35] this.players = y; [36] this.drinks = z; Source code cont. 14/04/15 43 [37] mycard = new MyCard(10, "red"); [38] Source code cont. [39] public static void main(string[] args) { [40] int counter = 2; [41] Game[] mygames = new Game[counter]; [42] for (int u=0; u<counter; u++){ [43] mygames[u] = new Game(u*u, 4); [44] [45] 14/04/

23 Draw the stack diagram Draw the stack diagram for when the execution reaches: 1. The end of line [38] for the first time 2. The end of line [38] for the second time 14/04/15 45 Solution AR(ctor) 370 AR(ctor) AR(ctor) 4 y 0 RA N/E this Object of class game.mycard?? - 10 points?? red color?? name?? next 0 num this Object of class game.game 4 players 0 drinks mycard Object of class mygames[0]?? mygames[1] SAR(for) 0 u SL Class card.card interface mygames 0-1 number counter SL Interface SP -1 RA 14/04/ N/E RV OK 46 Stack Heap 23

24 Solution Stack AR(ctor) AR(ctor) Object of class game.game 4 players 4 y 0 drinks AR(ctor) 1 z SP Object of class mygames[0] Object of class game.mycard N/E mygames[1]?? - 10 points this?? red color SAR(for) 1 u?? name Class SL?? interface num 1-2 number mygames counter Object of class game.game AR(main) Interface card.play SL 4-1 SP 1 drinks RA mycard N/E RV Heap Object of class game.mycard 10 red???? points color name next num class 24

The collections interfaces

The collections interfaces Generics in Java Advanced Programming 4/18/16 1 The collections interfaces Contains unique elements Maps unique keys to values 4/18/16 2 Collections in Java Array has a special language support Iterators

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = (Integer) myintlist.iterator().next(); // 3

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = myintlist.iterator().next(); // 3 3 Example

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? 10/26/10 1 Subtyping for behaviour the inner style class Reservation { date... ; customer... ; void print() { // print Date and Customer inner; class FlightReservation extends

More information

JAVA V Source files Java, winter semester

JAVA V Source files Java, winter semester JAVA Source files 17.10.2017 1 Unicode programs ~ Unicode comments, identifiers, char and string constants the rest is in ASCII (

More information

JAVA V Assertions Java, winter semester

JAVA V Assertions Java, winter semester JAVA Assertions 1 Assertion since Java 1.4 the statement with a boolean expression a developer supposes that the expression is always satisfied (evaluates to true) if it is evaluated to false -> error

More information

1.1. Annotations History Lesson - C/C++

1.1. Annotations History Lesson - C/C++ 1. Additions Thanks to Dr. James Heliotis. He started it all :) See also here: and see also here: and here: You need to use the tools from the Java release candidate 1 % bash % export PATH=/usr/local/j2sdk1.5.0-rc1/bin:$PATH

More information

Java Generics Java, summer semester

Java Generics Java, summer semester Java Generics Introduction similar to the templates in C#/C++ but only on first view typed arguments goal clear code type safety Motivational example without generics (

More information

Java Generics. Lecture CS1122 Summer 2008

Java Generics.  Lecture CS1122 Summer 2008 Java Generics http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf Lecture 17 -- CS1122 Summer 2008 Java Generics quick review When you see in Java, you are dealing with generics Generics allow

More information

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java. JAVA GENERICS Lecture CS110 Fall 018 Photo credit: Andrew Kennedy Java Collections Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob */ boolean

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? Reservation date customer print() FlightReservation flight seat print() TrainReservation train waggon seat print() 10/23/2009 1 Subtyping for behaviour the inner style class Reservation

More information

Parametric polymorphism and Generics

Parametric polymorphism and Generics Parametric polymorphism and Generics Today s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping.

More information

Software Engineering. Prof. Agostino Poggi

Software Engineering. Prof. Agostino Poggi Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma Software Engineering Generics Prof. Agostino Poggi public class ListOfIntegers { //... fields...

More information

Photo credit: Andrew Kennedy JAVA GENERICS

Photo credit: Andrew Kennedy JAVA GENERICS Photo credit: Andrew Kennedy JAVA GENERICS Lecture 17 CS2110 Spring 2017 Java Collections 2 Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob

More information

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping Outline 1 2 Outline 1 2 (Parametric) classes are classes that have Parameters A generic class with a concrete type parameter is an instance of the generic class The type parameter can be the type of variables,

More information

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA CSE 3302 Lecture 7: Polymorphism and generics 16 September 2010 Nate Nystrom UTA 2 Polymorphism poly = many morph = shape Allow a variable to contain values with different types 3 Subtype polymorphism

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 18 21:04:53 2018 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 19 19:36:29 2017 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages! Java Generics II Dr. Hyunyoung Lee!!! 1 Type System and Variance Within the type system of a programming language, variance refers to how subtyping between complex types

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping

More information

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed

More information

CS108, Stanford Handout #8. Java Generics

CS108, Stanford Handout #8. Java Generics CS108, Stanford Handout #8 Fall, 2007-08 Nick Parlante Java Generics Java generics (added in version 5) are a mixed bag. Some uses of generics are simple to understand and make the code cleaner. They are

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? Reservation date customer FlightReservation flight seat print() print() TrainReservation train waggon seat print() 10/4/2004 1 Subtyping for behaviour BETA style class Reservation

More information

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CSE 331 Software Design and Implementation. Lecture 15 Generics 2 CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

PARAMETRIC POLYMORPHISM

PARAMETRIC POLYMORPHISM PARAMETRIC POLYMORPHISM Java C#! Parametric polymorphism: " Java Generics and Generic C# for.net! The idea: the compiler is able to check parametric classes just looking at their definilon 1 Java Generics

More information

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B:

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Autumn 2013 Generics (Polymorphism) (Slides by Mike Ernst and David Notkin) 1 Varieties of abstraction Abstraction over computation: procedures int

More information

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes Problems Often you need the same behavior for different kind of classes Java Generics Use Object references to accommodate any object type Use Generic classes and Method The use of Object references induces

More information

CSE 331. Generics (Parametric Polymorphism)

CSE 331. Generics (Parametric Polymorphism) CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 Parametric polymorphism

More information

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes Java Generics 1 Concepts Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes 2 What Are Generics? Generics

More information

Java: exceptions and genericity

Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exceptions Exceptions

More information

Advanced Programming Generics Collections

Advanced Programming Generics Collections Advanced Programming Generics Collections The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements

More information

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #23 Announcements: Josh s office hours are now back in his office. HW6 now due Saturday. Partial solar eclipse tomorrow, starting at 1:52PM. Next one in August, 2017. See http://www.timeanddate.com/eclipse/list.html

More information

COMP6700/2140 Generic Methods

COMP6700/2140 Generic Methods COMP6700/2140 Generic Methods Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU March 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Generic Methods March 2017

More information

Exercise 8 Parametric polymorphism November 18, 2016

Exercise 8 Parametric polymorphism November 18, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T

More information

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm CSC 172 Data Structures and Algorithms Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm Agenda Administrative aspects Java Generics Chapter 1 ADMINISTRATIVE ASPECTS Workshops Workshops Workshops begin on this

More information

Java 5 New Language Features

Java 5 New Language Features Java 5 New Language Features Ing. Jeroen Boydens, BLIN prof dr. ir. Eric Steegmans http://users.khbo.be/peuteman/java5/ Enterprise Programming Last session. Jeroen Boydens 1. JDK v1.4: assert 2. Generics

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 7 Nadia Polikarpova Quiz 1: Does it compile? (Java) public class MyException extends Exception { Checked exception...

More information

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal  Version date: Java Brand Generics Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2005-03-03 Khalid Azim Mughal Java Brand Generics 1/40 Overview Introduction

More information

The list abstract data type defined a number of operations that all list-like objects ought to implement:

The list abstract data type defined a number of operations that all list-like objects ought to implement: Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two

More information

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Announcements. Java Graphics. Exceptions. Java Odds & Ends Java Odds & Ends Lecture 25 CS211 Fall 2005 Final Exam Wednesday, 12/14 9:00-11:30am Uris Aud Review Session Sunday, 12/11 1:00-2:30pm Kimball B11 Check your final exam schedule! Announcements For exam

More information

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

CMSC 202H. Containers and Iterators

CMSC 202H. Containers and Iterators CMSC 202H Containers and Iterators Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects Arrays are compiler-supported

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

Polymorphism and Interfaces. CGS 3416 Spring 2018

Polymorphism and Interfaces. CGS 3416 Spring 2018 Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that

More information

Generic programming in OO Languages

Generic programming in OO Languages CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 5 Gilad Bracha, Generics in the Java Programming Language Questions

More information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

Exercise Session Week 6

Exercise Session Week 6 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 6 Quiz 1: Does it compile? (Java) public class MyException extends Exception { Checked

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007 Advanced Topics in Java and on Security in Systems Effective Generics Eirik Eltvik 26 th of February 2007 Taking care when calling Legacy code Checks at compile-time is not always appropriate When? Legacy

More information

List ADT. Announcements. The List interface. Implementing the List ADT

List ADT. Announcements. The List interface. Implementing the List ADT Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as

More information

Polymorphism (generics)

Polymorphism (generics) Polymorphism (generics) CSE 331 University of Washington Michael Ernst Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1 + y1*y1); Math.sqrt(x2*x2

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Winter 2018 Generics UW CSE 331 Winter 2018 1 Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1

More information

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2018-15: Java

More information

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

CSE 331 Software Design and Implementation. Lecture 13 Generics 1 CSE 331 Software Design and Implementation Lecture 13 Generics 1 Zach Tatlock / Spring 2018 Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1

More information

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

Polymorphic (Generic) Programming in Java

Polymorphic (Generic) Programming in Java Polymorphic (Generic) Programming in Java We have used the fact that Java classes are arranged as a tree with the built in class Object at the root to write generic or polymorphic code such as the following

More information

Outline of lecture. i219 Software Design Methodology 6. Object oriented programming language 3. Kazuhiro Ogata (JAIST)

Outline of lecture. i219 Software Design Methodology 6. Object oriented programming language 3. Kazuhiro Ogata (JAIST) i219 Software Design Methodology 6. Object oriented programming language 3 Kazuhiro Ogata (JAIST) Outline of lecture 2 Primitive wrapper class Generics Primitive wrapper class 3 For each primitive type,

More information

CS 314 Midterm 2 Fall 2012

CS 314 Midterm 2 Fall 2012 Points off 1 2 3 4 5 Total off Net Score CS 314 Midterm 2 Fall 2012 Your Name_ Your UTEID Circle yours TA s name: John Zihao Instructions: 1. There are 5 questions on this test. 2. You have 2 hours to

More information

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics COMP1008 An overview of Polymorphism, Types, Interfaces and Generics Being Object-Oriented Exploiting the combination of: objects classes encapsulation inheritance dynamic binding polymorphism pluggability

More information

Effects of Static Type Specialization on Java Generic Collections (Technical Report) UMM Working Papers Series Work in progress

Effects of Static Type Specialization on Java Generic Collections (Technical Report) UMM Working Papers Series Work in progress Effects of Static Type Specialization on Java Generic Collections (Technical Report) UMM Working Papers Series Work in progress Elena Machkasova, Elijah Mayfield, Nathan Dahlberg, J. Kyle Roth University

More information

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

COMP 250. Lecture 29. interfaces. Nov. 18, 2016 COMP 250 Lecture 29 interfaces Nov. 18, 2016 1 ADT (abstract data type) ADT s specify a set of operations, and allow us to ignore implementation details. Examples: list stack queue binary search tree priority

More information

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList: Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Properties of an identifier (and the object it represents) may be set at

Properties of an identifier (and the object it represents) may be set at Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value

More information

CMSC 202. Containers

CMSC 202. Containers CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.

More information

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types generics enable types (classes and interfaces) to be parameters when defining

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

CS 307 Midterm 2 Spring 2011

CS 307 Midterm 2 Spring 2011 Points off 1 2 3 4 5 Total off Net Score Exam Number: CS 307 Midterm 2 Spring 2011 Name UTEID login name TA's Name: Dan Muhibur Oliver (Circle One) Instructions: 1. Please turn off your cell phones and

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Overview of Java s Support for Polymorphism

Overview of Java s Support for Polymorphism Overview of Java s Support for Polymorphism Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. 1. The Nose class... b) will not compile because the m1 method parameter should be named n, not x. 2. The Ears class...

More information

COMP6700/2140 Generic Types

COMP6700/2140 Generic Types COMP6700/2140 Generic Types Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 24 March 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Generic Types 24 March

More information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013 1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it

More information

Java. Platforms, etc.

Java. Platforms, etc. Java Platforms, etc. Java object oriented (almost) all is object interpreted source code (.java) compiled to the bytecode bytecode (.class) interpreted by the virtual machine platform independent programs

More information

Exercise 8 Parametric polymorphism November 17, 2017

Exercise 8 Parametric polymorphism November 17, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 8 Parametric polymorphism November 17, 2017 Task 1 Implement a list in Java or C# with two methods: public void add(int i, Object el) public Object

More information

CS/ENGRD 2110 SPRING 2018

CS/ENGRD 2110 SPRING 2018 CS/ENGRD 2110 SPRING 2018 Lecture 7: Interfaces and http://courses.cs.cornell.edu/cs2110 1 2 St Valentine s Day! It's Valentines Day, and so fine! Good wishes to you I consign.* But since you're my students,

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-14: Java

More information

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018 CSE 331 Software Design and Implementation Lecture 14 Generics 1 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due Thursday Homework 6 due Thursday Midterm grades and feedback will

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

CSE 331 Software Design and Implementation. Lecture 14 Generics 1 CSE 331 Software Design and Implementation Lecture 14 Generics 1 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due Thursday Homework 6 due Thursday Midterm grades and feedback will

More information

CS 314 Midterm 2 Spring 2013

CS 314 Midterm 2 Spring 2013 Points off 1 2 3 4 5 Total off Net Score CS 314 Midterm 2 Spring 2013 Your Name Your UTEID Circle yours TA s name: Donghyuk Lixun Padmini Zihao Instructions: 1. There are 5 questions on this test. The

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10 Generics Computer Science and Engineering College of Engineering The Ohio State University Lecture 10 A Simple Component Client-side view: Pencil interface Pencil { String tostring(); void setcolor(colors

More information

Introducing Generics

Introducing Generics Generics Introducing Generics Generics allow reference types (classes, interfaces, and array types) and methods to be parameterized with type information. An abstract data type (ADT) defines both the types

More information

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability. Scope vs. Lifetime It is usually required that the lifetime of a run-time object at least cover the scope of the identifier. That is, whenever you can access an identifier, the run-time object it denotes

More information

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed. Name Solution The exam is closed book and closed electronics. One page of notes is allowed. The exam has 6 regular problems and 1 bonus problem. Only the regular problems will count toward your final exam

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Generalized Code. Fall 2011 (Honors) 2

Generalized Code. Fall 2011 (Honors) 2 CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy

More information

Java. Platforms, etc.

Java. Platforms, etc. Java Platforms, etc. Java object oriented (almost) all is object interpreted source code (.java) compiled to the bytecode bytecode (.class) interpreted by the virtual machine platform independent programs

More information

AP CS Unit 7: Interfaces. Programs

AP CS Unit 7: Interfaces. Programs AP CS Unit 7: Interfaces. Programs You cannot use the less than () operators with objects; it won t compile because it doesn t always make sense to say that one object is less than

More information

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface Java Collections Framework Collection: a group of elements Based Design: Software 1 with Java Java Collections Framework s s Algorithms Recitation No. 6 (Collections) 2 Collection s Online Resources Collection

More information