Generics and Type Parameters

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
Generics and the ArrayList Class
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
©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.
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.
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.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Introduction to 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.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
CMSC 202 ArrayList Aug 9, 2007.
Java Generics.
Java Arrays and ArrayLists COMP T1 #5
4. Java language basics: Function
CSC 243 – Java Programming, Spring 2014
Templates.
Chapter 20 Generic Classes and Methods
Generics and Subtyping
A tree set Our SearchTree class is essentially a set.
Generics, Lambdas, Reflections
Java Algorithms.
Templates.
Winter 2018 CMPE212 9/21/2018 CMPE212 – Stuff…
Topic 6 Generic Data Structures
Objects First with Java CITS1001
Generics.
Winter 2018 CMPE212 11/12/2018 CMPE212 – Stuff…
Chapter 19 Generics Dr. Clincy - Lecture.
CSE 331 Software Design and Implementation
Generics (Parametric Polymorphism)
Polymorphism.
Lecture 26: Advanced List Implementation
A tree set Our SearchTree class is essentially a set.
CSE 331 Software Design and Implementation
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
CMSC 202 ArrayList Aug 9, 2007.
CISC124 Assignment 4 on Inheritance due next Friday.
Sorting Chapter 8.
A few of the more significant changes and additions. James Brucker
CSE 331 Software Design and Implementation
slides created by Marty Stepp
CMSC 202 Generics.
Final Jim Brucker.
Binary search (13.1) binary search: Locates a target value in a sorted array/list by successively eliminating half of the array from consideration. How.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 11 Inheritance and Polymorphism Part 2
Object-Oriented Programming Part 3 Bank Account Embezzling
Chapter 21 Generics.
Chapter 19 Generics.
CSE 143 Lecture 21 Advanced List Implementation
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Chapter 19 Generics.
Presentation transcript:

Generics and Type Parameters

Simple Generic Class Example you have already written: public class ArrayIterator<T> implements Iterator<T> { private T[] array; public ArrayIterator(T[] a) { this.array = a; } T get(int index) { return a[index]; } new ArrayIterator<String>( string_ array ); new ArrayIterator<Double>( double_array );

Class Type Parameters is allowed only on instance members Java processes type parameters using "type erasure". As a result, a class type param cannot be used on static members. public class MyClass<T> { private T attribute; // OK private static T x; // ERROR public T getAttribute() { // OK return attribute; } public static T newInstance() // ERROR

Type Parameter with Bound You can limit type parameters using "extends" and "super". T is any type that implements Runnable: public class TaskManager<T extends Runnable> { private List<T> tasks; public void runAll() { for(Task t: tasks) t.run(); } public void addTask(T task) { tasks.add(task);

Wildcard Character ? Means "anything". Can use "?" on non-generic methods, too. Can be used with bounds, like "? extends Valuable". public void printAll(List<?> list) { // forEach is same as "for-each" loop // requires Java 8 list.forEach( (x) -> System.out.println(x) ); }

Demo: MoneyUtil.sortByCurrency The signature of the method is: public static void sortByCurrency( List<? extends Valuable> list) { // sort items by currency } But this code won't compile. Why? How to fix? List<Coin> coins = Arrays.asList( new Coin(5,"Cents"),new Coin(1,"Baht")); sortByCurrency( coins ); // ERROR

Generic Methods A static method can have its own type parameter. It can be method in an ordinary (non-generic class). java.util.Arrays and java.util.Collections are examples public static <E> reverse(E[ ] array) { int size = array.length - 1; for(int k=0; k<size/2; k++) { E temp = a[k]; a[k] = a[size-k]; a[size-k] = temp; }

Calling Generic Methods The caller does not mention the type parameter. Java compiler infers the actual type from context. Number[] array = new Number[]{1, 2, 3}; reverse( array ); // Java infers E = Number String[] words = {"a", "b", "c"}; reverse( words ); // Java infers E = String

Example Write a generic "max" method. Find "max" of two objects that implement Comparable. public static <E extends Comparable<E>> E max(E a, E b) { if (a.compareTo(b) > 0) return a; return b; } // This method has a problem: String m = max("Cat", "Dog"); // OK Coin m2 = max(new Coin(5), new Coin(10)); // Compile error // Coin implements Comparable<Valuable>

"? super E" Look at Collections.fill - replace all elements in list with copies of an object. It works even if the value (obj) is from a subclass of the List type. public static <T> void fill(List<? super T>, T obj) ; // This should work: fill a list of Number // with an Integer (Integer extends Number) List<Number> list = new ArrayList<>(10); ... // add some stuff to list Collections.fill( list, new Integer(5) );

"? super E" Collections.sort() - can sort List using any Comparator that accepts T or a superclass of T. Can you see why this is necessary? public static <T> sort(List<T> list, Comparator<? super T> comp) List<Money> money = // create some money Comparator<Valuable> compByCurrency = (a,b) -> a.getCurrency().compareTo(b.getCurrency); // This should work: Collections.sort( money, compByCurrency);

Exercise max accepts 2 objects that implement Comparable<E> Coin implements Comparable<Valuable> How can we make max( ) work with Coin? static <E extends Comparable<E>> max(E a, E b) { if (a.compareTo(b)>0) return a; return b; } String s = max("Alpha", "Beta"); // OK! Coin m = max(new Coin(5), new Coin(10)); // ERROR!

Demo: CoinUtil.filterByCurrency Always returns List<Valuable>

Summary 1. Class type parameters apply to instance members only. 2. Static methods can have their own type parameter. 3. Bounds and wildcards: ? = match anything (can be used on any method) <? super E> = match superclass of E <E extends Foo> = bound on type param E Type parameters are used a lot in API docs, so you need to be able to read and understand them.

References Core Java for the Impatient - has a chapter on generics with many examples Big Java, Chapter 18 (Generics) Generics.doc - my write-up on generics and type param