Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.

Slides:



Advertisements
Similar presentations
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Advertisements

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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
Java Generics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) Generics.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L14 (Chapter 21) Generics.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Java Generics.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
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.
 2005 Pearson Education, Inc. All rights reserved Generics.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Introduction to Generics
CIS 270—Application Development II Chapter 18-Generics.
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
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.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
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.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Sixth Lecture ArrayList Abstract Class and Interface
CIS265/506 Cleveland State University – Prof. Victor Matos
John Hurley Cal State LA
Java Generics.
Chapter 20 Generic Classes and Methods
Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
CS2013 Lecture 3 John Hurley Cal State LA.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 8 Class Inheritance and Interfaces
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

Chapter 21 Generics 1

Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse with compile-time type safety 2

What is Generics? Generics is the capability to parameterize types. Can define class or method with generic types Compiler substitutes with concrete types. Example: ▫a generic stack class that stores elements of a generic type. ▫Can create stack of strings and stack of numbers. ▫String and Number are concrete types. 3

Generic Methods Method overloading – can have several identical methods with same number of arguments, but of different types (printArray for Integer, Double, Character) Can replace with one generic method 4

Generic Methods Syntax: Public static void print (E[] list) Type parameter section in angle brackets before return type of method Can be comma separated list. 5

Generic Methods 6 public static void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } public static void print(Object[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

Generic Methods Generic methods can be defined in ordinary classes. 7 public class ArrayAlg{ public static T getMiddle(T[] a){ return a[a.length/2]; }

Pre-JDK 1.5 Generics introduced in JDK 1.5 Prior versions of Java used inheritance Parameters can be of type Object 8

Why Generics? What was wrong with using Object? ▫Casting is necessary when return value is of general type AND ▫No error checking - the type of object can keep changing. 9

Why Generics? Key benefit: generics enable errors to be detected at compile time rather than at runtime. With generic class or method, can specify types of objects that the class or method may work with. Attempt to use class or method with incompatible object -> compilation error. 10

Generic Type 11 Generic Instantiation Runtime error Compile error Improves reliability

Why Do You Get a Warning? public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); list.add("Java Programming"); } 12 JDK 1.5 generics. (Types may not be compatible.)

Fix the Warning public class ShowUncheckedWarning { public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList (); list.add("Java Programming"); } 13 No compile warning on this line. `

Generic ArrayList in JDK

No Casting Needed ArrayList list = new ArrayList (); list.add(5.5); // 5.5 is automatically converted to new Double(5.5) list.add(3.0); // 3.0 is automatically converted to new Double(3.0) Double doubleObject = list.get(0); // No casting is needed double d = list.get(1); // Automatically converted to double 15

Declaring Generic Classes and Interfaces 16 GenericStack

Bounded Generic Type Syntax: Use keyword extends. Both E and BoundingType can be a class or interface. Separate several bounds with & (comma separates type variables) 17

Bounded Generic Type 18 public static void main(String[] args ) { Rectangle rectangle = new Rectangle(2, 2); Circle9 circle = new Circle9(2); System.out.println("Same area? " + equalArea(rectangle, circle)); } public static boolean equalArea(E object1, E object2) { return object1.getArea() == object2.getArea(); }

C++ C++ templates are like Java generics. C++ creates multiple copies of code for different possible template instantiations. Java uses a single, general copy of code 19

Erasure Java uses type erasure to create one version of code with a raw type. Type variables are erased and replaced by their bounding types What if no bounding types? Object Cast - method calls that return raw type. 20

Raw Type and Backward Compatibility // raw type ArrayList list = new ArrayList(); 21 This is roughly equivalent to ArrayList list = new ArrayList ();

Raw Type is Unsafe Max.max("Welcome", 23); 22 // Max.java: Find a maximum object public class Max { /** Return the maximum between two objects */ public static Comparable max(Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } Runtime Error:

Make it Safe Max.max("Welcome", 23); 23 // Max1.java: Find a maximum object public class Max1 { /** Return the maximum between two objects */ public static > E max(E o1, E o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } Compile-time Error:

Limitations Primitive types cannot be used for type parameter - use wrapper classes. Type inquiries (instanceof) yield only the raw types. Arrays cannot be of generic types. (Use ArrayList to collect generic types.) 24

Limitations (cont.) Cannot instantiate generic types. Error: new E(). Type variables cannot be used in a static context - which type should they be?! 25

Inheritance No relationship between Pair and Pair, no matter how S and T are related Why not? Code won’t always work (You can insert Double to ArrayList of Number, not to ArrayList of Integer) 26

Wildcards Why wildcards are necessary? See this example. 27 WildCardDemo1 ? unbounded wildcard ? extends T bounded wildcard ? super T lower bound wildcard WildCardDemo2WildCardDemo3

Wildcards ? unbounded wildcard ? extends T bounded wildcard T or any of its subclasses ? super T lower bound wildcard T or any of its superclasses 28

Generic Types and Wildcard Types 29

Wildcards Advantage: Wildcards provide flexibility when passing parameterized types to a method. Disadvantage: Cannot be used as type name throughout method body. 30

Avoiding Unsafe Raw Types Use new ArrayList () Instead of new ArrayList(); 31 TestArrayListNew Run

Erasure and Restrictions on Generics Implementation of generics: type erasure. The compiler uses the generic type information to compile the code, but erases it afterwards. Generic information is not available at run time. Backward-compatibility with legacy code that uses raw types. 32

Compile Time Checking For example, the compiler checks whether generics is used correctly for the following code in (a) and translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type. 33

Important Facts It is important to note that a generic class is shared by all its instances regardless of its actual generic type. GenericStack stack1 = new GenericStack (); GenericStack stack2 = new GenericStack (); Although GenericStack and GenericStack are two types, there is only one class GenericStack loaded into the JVM. 34

Designing Generic Matrix Classes Objective: This example gives a generic class for matrix arithmetic. This class implements matrix addition and multiplication common for all types of matrices. 35 GenericMatrix

UML Diagram 36