Effective Java: Generics Last Updated: Spring 2009.

Slides:



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

Java Review Interface, Casting, Generics, Iterator.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
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)
Java Generics.
1 Generics, Type Safety, and Dynamic Data Structures.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
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.
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
ArrayList, Multidimensional Arrays
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
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.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION GENERICS/PARAMETRIC POLYMORPHISM Autumn 2011 We We Abstraction.
©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.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
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.
CIS265/506 Cleveland State University – Prof. Victor Matos
More Generics רובי בוים ומתי שמרת
Chapter 20 Generic Classes and Methods
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Effective Java: 3rd Edition Generics
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

Effective Java: Generics Last Updated: Spring 2009

Generics 2 Agenda Material From Joshua Bloch Effective Java: Programming Language Guide Cover Items “Generics” Chapter Bottom Line: Generics are safer, than raw types But generics are also more complex Raw types are allowed for backwards compatibility

Generics 3 Item 23: Don’t Use Raw Types in New Code A class (interface) with one or more type parameters is a generic class (interface) Examples: List is a raw type List is a generic interface List is a parameterized type String is the actual type parameter corresponding to E

Generics 4 Example: Replacing raw types // Now a raw collection type – don’t do this private final Collection stamps = …; // Contains only Stamps // Erroneous insertion of coin into stamp collection stamps.add(new Coin(…)); // Oops! We’re set up for ClassCastException later // Parameterized collection type - typesafe private final Collection stamps = …; stamps.add(new Coin(…)); // result is instead a compile time error, which is good // Now a raw iterator type – don’t do this! for (Iterator I = stamps.iterator(); i.hasNext(); ) { Stamp s = (Stamp) i.next(); // Throws ClassCastException …// Do something with the stamp } // for-each loop over parameterized collection – typesafe for (Stamp s: stamps) { // No cast …// Do something with the stamp }

Generics 5 Example: Mixing generic and raw types // Uses raw type (List) – fails at runtime public static void main(String[] args) { List strings = new ArrayList (); unsafeAdd(strings, new Integer(42)); String s = strings.get(0); //Exception from compiler generated cast } // note use of raw types private static void unsafeAdd(List list, Object o) { list.add(o); } // There is a compile time warning: Test.java:10: warning: unchecked call to add(E) in raw type List list.add(o); ^ // If we ignore the warning, and run the program, we get a ClassCastException // where the compiler inserted the cast // If we try the following, it won’t compile (see Item 25) private static void unsafeAdd( List list, Object o) { list.add(o);}

Generics 6 Example: Using Wildcards // Use of raw type for unknown element type – don’t do this! static int numbElementsInCommonSet (Set s1, Set s2) { int result = 0; for (Object o1: s1) { if (s2.contains(o1)) result ++; } return result; } // Unbounded wildcard type – typesafe and flexible static int numbElementsInCommonSet (Set s1, Set s2) { int result = 0; for (Object o1: s1) { if (s2.contains(o1)) result ++; } return result; } // We’ll revisit this type of example in Item 27

Generics 7 Example: Using Wildcards // Do the question marks really buy you anything? // Answer: Wildcard is typesafe, // because you can’t add *anything* (except null) to Collection // Two exceptions: Raw types ok in 1) Class Literals: List.class, not List.class 2) instanceof operator if (o instanceof Set) { // raw type ok Set m = (Set ) o; // Wildcard type // Why the exceptions? Compatibility with old Java

Generics 8 Item 24: Eliminate Unchecked Warnings Generics result in many compiler warnings Eliminate them As a last resort, suppress the warnings Do so as at local a level as possible Options are class down to local declaration Use annotation Some are easy: Set exaltation = new HashSet(); // warning Set exaltation = new HashSet (); // no warning

Generics 9 Item 25: Prefer Lists to Arrays Lists play well with generics Generic array creation not typesafe (hence illegal) No new List [], new List [], or new E[] Arrays are covariant, Generics are Invariant If Sub is a subtype of Super Then Sub[] is a subtype of Super[] But List is not a subtype of List Arrays are reified; Generics are erased Generics are compile time only

Generics 10 Example: Covariance vs. Invariance // Fails at runtime Object[] objectArray = new Long[1]; objectArray[0] = “I don’t fit in!”; // Throws ArrayStoreException // Won’t compile List o1 = new ArrayList (); o1.add(“I don’t fit in!”); // Incompatible types Not compiling is better than a runtime exception. This is basically an argument for why invariance is preferable to covariance for generics. Later, we’ll see how to relax this.

Generics 11 Example: Illustrating type (non) safety // Why generic array creation is illegal – won’t compile 1) List [] stringLists = new List [1]; // won’t compile 2) List intList = Arrays.asList(42); 3) Object[] objects = stringLists; 4) Objects[0] = intList; 5) String s = stringLists[0].get(0); // compiler generated cast to String Suppose 1) compiled (it won’t) 2) Creates and initializes a List with one element 3) Stores the List object into an Object array variable, note, this is legal because arrays are covariant 4) Stores the List into the sole element of the Object array this succeeds because generics are implemented by erasure. The runtime type is simply List[], so there is no exception 5) Now, we’ve stored a List instance into an array that is declared to hold only List instances. So, we get a ClassCastException

Generics 12 Item 26: Favor Generic Types Parameterize collection declarations Use the generic types Implementer has to work harder But clients have type safety Stack example: How to support this? public static void main (String[] args) { Stack stack = new Stack (); for (String arg: args) { stack.push(arg);} while (!stack.isEmpty()) { …stack.pop()…} }

Generics 13 Example: Converting collection to generics public class Stack { // Original Version – no generics private Object [] elements; private int size = 0; private static final int CAP = 16; public Stack() { elements = new Object [CAP];} public void push( Object e ) { ensureCapacity(); elements [size++] = e; } public Object pop() { if (size == 0) { throw new ISE(…); } Object result = elements [--size]; elements[size] = null; return result; } // remainder of Stack omitted – See Bloch

Generics 14 Example: Converting collection to generics public class Stack { // First cut at generics – won’t work private E [] elements; // Alternate 2: Leave as Object private int size = 0; private static final int CAP = 16; public Stack() { elements = new E [CAP];} // error; generic array creation // Alternate 1: = new (E[]) Object [CAP];} // warning //public Stack() { elements = new (E[]) Object [CAP];} // warning suppressed public void push( E e ) { ensureCapacity(); elements [size++] = e; } public E pop() { if (size == 0) { throw new ISE(…); } E result = elements [--size]; // Error for Alternate 2; also cast and suppress warning elements[size] = null; return result; }

Generics 15 Item 27: Favor Generic Methods Just as classes benefit from generics So do methods Writing generic methods is similar to writing generic types

Generics 16 Example: Generic method // Uses raw types – unacceptable! (Item 23) public static Set union (Set s1, Set s2) { Set result = new HashSet(s1); // Generates a warning result.addAll(s2); // Generates a warning return result; } // Generic method public static Set union (Set s1, Set s2) { Set result = new HashSet (s1); result.addAll(s2); return result; } // The first is the type parameter list // Example from the java.util.Collection // The generics can get a bit redundant… Map > anagrams = new HashMap >();

Generics 17 Item 28: Use bounded wildcards to increase API Flexibility public class Stack { // First cut at generics – won’t work public Stack() public void push( E e ) public E pop() public boolean isEmpty() } // pushAll method without a wildcard type – deficient! public void pushAll( Iterable src) { for (E e : src) { push(e); } } // wildcard type for parameter that serves as an E producer public void pushAll( Iterable src) { for (E e : src) { push(e); } } // wildcard type for parameter that serves as an E consumer public void popAll ( Collection dst) { while (!isEmpty()) { dst.add(pop()); } }

Generics 18 The PECS mnemonic // PECS – producer extends, consumer super // Recall earlier example public static Set union (Set s1, Set s2) // Are parameters consumers or producers? ( Producers, so, extend) public static Set union (Set s1, Set s2) // Note that return type should still be Set, not Set // otherwise, clients will have to use wildcards… Set integers = … Set doublse = … Set numbers = union ( integers, doubles); // compiler error Set numbers = union. ( integers, doubles); // type parameter works // max example public static > T max (List list ) // original public static > T max (List list) // PECS

Generics 19 Item 29: Consider typesafe heterogeneous Containers // Typesafe heterogeneous container pattern – implementation public class Favorites private Map, Object> favorites = new HashMap(, Object>(); public void putFavorite(Class type, T instance) { if (type == null) { throw new NPE… } favorites.put (type, instance); } public T getFavorite(Class type) { return type.cast(favorites.get(type)); } // Fairly subtle stuff…