Generics CompSci 230 S2 2015 Software Construction.

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
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.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
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.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
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.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
ArrayList, Multidimensional Arrays
Java Interfaces, Lists and Generics essentials
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
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.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Recitation 5 Enums and The Java Collections classes/interfaces 1.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
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.
Object Oriented Programming in Java Habib Rostami Lecture 7.
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.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Java Generics.
Chapter 20 Generic Classes and Methods
Implementing ArrayList Part 1
Interfaces and Inheritance
Generics A Brief Review 16-Nov-18.
Generics 27-Nov-18.
ArrayLists 22-Feb-19.
Java Programming Language
Review: libraries and packages
TCSS 143, Autumn 2004 Lecture Notes
Generics 2-May-19.
Chapter 19 Generics.
Presentation transcript:

Generics CompSci 230 S Software Construction

Agenda & Reading  Topics:  Introduction  Fundamentals of generic types  Generics & Subtyping  Type wildcards  Reading  The Java Tutorial:  Generics Generics 092

What Are Generics?  Generics abstract over Types  Classes, Interfaces and Methods can be Parameterized by Types  Generics provide increased readability and type safety 093

Example: Item BookMovieCD Priced > Shirt public class Item { protected String title; public Item(String title) { this.title = title; } public String getTitle() { return title; } public class Book extends Item { private String author; public Book(String title, String author) { super(title); this.author = author; }... public String toString() { return "Book: '" +... } public class Movie extends Item { private int year; public Movie(String title, int year) { super(title); this.year = year; }... public String toString() { return... } public class CD extends Item implements Priced { private double price;... public doublegetPrice() {...} } public interface Priced { public double getPrice(); } 094

Interface java.util.List  Java’s original specification for list data structures  (non-generic – Java 1.4)  This interface defines a contract for each of the operations of a list, i.e.  What it takes in  What it returns  What the state of the list should be afterwards  Individual implementations should fulfil the contract – in whatever way they see fit public interface List { public boolean add(Object o); public boolean add(int i, Object); public Object remove(int i); public Object remove(Object o); public Object get(int i); public int indexOf(Object o); public boolean contains(Object o); public int size(); public Iterator iterator(); //plus others } 095

Why generics?  Type Safety!  Array:  We must say what’s in the array  ArrayList:  But anything could go in the ArrayList;  We can pass in Movie, Book and CD instances as arguments to add( ) as its formal argument type is Object  However because get( )’s return type is Object, we need to downcast the result to the appropriate subclass Person[] people = new Person[25]; people[0] = "Sally"; // syntax error ArrayList people = new ArrayList(); people.add("Sally"); List items = new ArrayList(); items.add(new Movie("Psycho",1960)); items.add(new Book("LOTR","Toklien")); for (int i = 0; i < items.size(); i++) { Item item = (Item)items.get(i); System.out.println(i+": "+item.getTitle()); } 096

List of Items  We want items to store only objects of type Item (or its subclasses)  What happens if it doesn't?  What exactly would happen?  Will this compile?  Will it run? items.add(new Movie("Psycho",1960)); items.add("Terminator"); for (int i = 0; i < items.size(); i++) { Item item = (Item)items.get(i); System.out.println(i+": "+item.getTitle()); } Runtime error Example: TestsApp 097

Compile-time vs. Runtime errors  Moral of the story: we can’t rely on the compiler to detect/predict all errors (although we’d like to)  What compilers can detect:  Syntactic/”obvious” errors, e.g: accessing an undeclared variable; calling an undefined method; mismatching braces/brackets; assigning a value to a variable of incompatible type  What compilers can't:  Logical errors, unexpected behaviours only observable at runtime e.g. accessing a null field, bogus user input, nondeterministic code  Most lead to exceptions being thrown like NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, ClassCastException 098

What can we do instead?  Create a specialised List for Item? NO!  Repetitive  Inefficient  Hardly scalable public class ItemList { private List items; public ItemList() { items = new ArrayList(); }... } public class StringList { private List items; public StringList () { items = new ArrayList(); } public void add(String s) { items.add(s); }... } public class IntList { private List items; public IntList() { items = new ArrayList(); } public void add(Integer i) { items.add(i); }... } 099

Answer: Generics!  With generics, we can make List a generic type  By parameterising List with the type Item we are guaranteed that any instance of this special List would only contain objects of type T (or its subclasses) 0910

Example:  Instead of saying: List words = new ArrayList();  You'll have to say:  Replaces runtime type checks with compile-time checks  No casting; instead of String title = (String) words.get(i); you use  Some classes and interfaces that have been “genericized” are: Vector, ArrayList, LinkedList, Hashtable, HashMap, Stack, Queue … List words = new ArrayList (); String title = words.get(i); 0911

More Examples  The letter E as the type parameter for elements in generic collections  Examples: ArrayList words = new ArrayList (); ArrayList nums = new ArrayList (); ArrayList words = new ArrayList (); list1.add(new String("HA")); list1.add(new String("HE"));; String s1 = list1.get(0); String s2 = list1.get(1); System.out.println(s1 + " " + s2); ArrayList nums = new ArrayList (); nums.add(new Integer(4)); nums.add(new Integer(5)); Integer i1 = nums.get(0); Integer i2 = nums.get(1); 0912

for-each loop  The for-each loop is used to access each successive value in a collection of values.  Syntax:  Example: ArrayList words = new ArrayList ();... for (String str : words) { System.out.println(str); } for (Base_Type var :Collection_Object) Statement; 0913

Generics and type safety  Good news: the compiler can help us prevent type errors  The compiler enforces the parameterised type List to only accept and return instances of Item (or its subclasses) List genericsItems = new ArrayList (); genericsItems.add(new Movie("Psycho",1960)); genericsItems.add("Terminator"); List genericsItems = new ArrayList (); genericsItems.add(new Movie("Psycho",1960)); genericsItems.add(new Book("LOTR","Tolkien")); genericsItems.add(new CD("Ozomatli",2.50)); for (int i = 0; i < genericsItems.size(); i++) { Item item = genericsItems.get(i); System.out.println(i+": "+item.getTitle()); } COMPILE-TIME ERROR Example: TestGenericsApp 0914

Generics Vs No Generics public class Arraylist { private E[] elementData;... //stuff public boolean add(E o) { elementData[size++] = o; return true; } public E get(int i) { return elementData[i]; } public class ArrayList { private Object[] elementData;... //stuff public boolean add(Object o) { elementData[size++] = o; return true; } public Object get(int i) { return elementData[i]; } ‘Generic type’ ‘Non-generic type’ ArrayList items = new ArrayList (); ‘Type argument’ ‘Parameterised type’ ‘Type parameter’ /‘Type variable’ 0915

Example: Comparable + Generics  Comparable Interface: java.lang.Comparable  int compareTo() returns an integer result:  Returns negative if the object it is applied to is less than the argument  Returns zero if the object it is applied to is equal to the argument  Returns positive if the object it is applied to is greater than the argument public interface Comparable { public int compareTo(Object obj); } public class Person implements Comparable { protected String irdNumber;... public int compareTo(Object obj) { if (!(obj instanceof Person)) { throw new ClassCastException("Not a Person"); } Person p = (Person) obj; return irdNumber.compareTo(p.getIRD()); } without Generics public class Person implements Comparable protected String irdNumber;... public int compareTo(Person p) { return irdNumber.compareTo(p.getIRD()); } with Generics 0916

Generics & Subtyping  Is a List of String a List of Object?  Is a List of Movie a List of Item?  If this is allowed, then we can  add items to the list of Movie by accessing genericsItems  attempt to assign an Item to a Movie object!!! List ls = new ArrayList (); ls.add("Hello");... List lo = ls; List lm = new ArrayList (); lm.add(new Movie("Psycho",1960));... genericsItems = lm; COMPILE-TIME ERROR genericsItems.add(new Item("Sample")); Movie m1 = lm.get(0); ERROR 0917

Generics & Subtyping  So  Movie is a subtype of Item, and G is some generic type declaration  It is not the case that G is a subtype of G  But  We normally think that a List is a List assuming that Drive is a subtype of Person.  We will need to look at Wildcards! 0918

Type wildcards  Here’s a simple (no generics) method to print out any list (without generics):  The above still works in Java 1.5, but now it generates warning messages  Next, here is an attempt using Generics  But it only takes a list of Object, but it is not a supertype of all kinds of lists. public static void printCollection(List c) { for (Iterator i = c.iterator(); i.hasNext(); ) { System.out.println(i.next()); } public static void printCollection(List c) { for (Iterator i = c.iterator(); i.hasNext(); ) { System.out.println(i.next()); } uses unchecked or unsafe operations. Note: Recompile with - Xlint:unchecked for details. List mylist = new ArrayList(); … printCollection(mylist); List mylist = new ArrayList (); printCollection(mylist); //ERROR 0919

Type wildcards  You should eliminate all errors and warnings in your final code, so you need to tell Java that any type is acceptable:  (i.e. any type) signifies an unbounded wildcard. (pronounced “list of unknown”)  a list whose element type matches anything = called wildcard type public static void printCollection(List c) { for (Iterator i = c.iterator(); i.hasNext(); ) { System.out.println(i.next()); } List movieList = new ArrayList (); movieList.add(new Movie("Psycho",1960)); printCollection(movieList); List myStrlist = new ArrayList (); myStrlist.add("Hello"); printCollection(myStrlist); 0920

for-each statement  for( type var : array) {...} or for( type var : collection ) {...}  Example: public static void printCollection(List c) { for (Object e: c) { System.out.println(e); } List movieList = new ArrayList (); movieList.add(new Movie("Psycho",1960)); printCollection(movieList); List myStrlist = new ArrayList (); myStrlist.add("Hello"); printCollection(myStrlist); 0921

Subtyping in generics  Consider the following method:  The type rules say that the above method can only be called on lists of exactly Item:  It cannot, for instance, be called on a List  But, how to accept a list of any kind of item (e.g. List, List ) Item Movie public static void printItemCollection(List il) { for (Item i: il) { System.out.println(i.getTitle()); } public static void printItemCollection(List il) { for (Item i: il) { System.out.println(i.getTitle()); } 0922

Bounded Wildcards  (i.e. any subclass of T, including T itself) signifies a bounded wildcard  (i.e. any type) signifies an unbounded wildcard  Note: is equivalent to  => Item is the upper bound of the wildcard  Note that since wildcards denote unknown types, there are limitations on how a wildcard variable can be used  It is now illegal to write into the list in the body of the method  Such limitations are compiler enforced  It is an unknown subtype of Item. Since we don’t know what type it is, we don’t know if it is a supertype of Movie; it might or might not be such a supertype, so it isn’t safe to pass a Movie there. public static void printItemCollection(List il) { il.add(new Movie("Psycho",1960)); } COMPILE-TIME ERROR 0923