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.

Slides:



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

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L14 (Chapter 21) Generics.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
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.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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.
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.
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
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
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.
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.
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.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
(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.
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 11 Inheritance and Polymorphism
CIS265/506 Cleveland State University – Prof. Victor Matos
John Hurley Cal State LA
Chapter 20 Generic Classes and Methods
Continuing Chapter 11 Inheritance and Polymorphism
Generics.
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Generics.
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 11 Inheritance and Polymorphism Part 2
Review: libraries and packages
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

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 why generic types can improve reliability and robustness (§21.3). F To declare and use generic methods and bounded generic types (§21.4). F To use raw types for backward compatibility (§21.5). F To know wildcard types and understand why they are necessary (§21.6). F To understand that all instances of a generic class share the same runtime class file (§21.7). F To convert legacy code using JDK 1.5 generics (§21.8). F To design and implement a generic matrix class (§21.9).

Example: Pre_Java5 3

See these warnings before? 4 Warnings from last compilations uses unchecked or unsafe operations Recompile with –Xlint unchecked for details

5 Why Do You Get a Warning? public class TestArrayList { public static void main(String[] args) { // Create a list to store cities java.util.ArrayList cityList = new java.util.ArrayList(); // Add some cities in the list cityList.add("London"); } To understand the compile warning on this line, you need to learn JDK 1.5 generics.

6 ArrayList public ArrayList() Constructs an empty list with an initial capacity of ten. add public boolean add(E e) Appends the specified element to the end of this list.E Specified by:add in interface Collection Specified by:add in interface List Overrides:add in class AbstractList Parameters:e - element to be appended to this list Returns:true (as specified by Collection.add(E))addCollectionEaddListEaddAbstractListECollection.add(E)

7 Generic Type Generic Instantiation Runtime error Compile error Improves reliability Restricts to type Date

8 Generic ArrayList in JDK 1.5

9 Fix the Warning in BJ_Java5 import java.util.*; public class TestArrayListNew { public static void main(String[] args) { ArrayList cityList = new ArrayList (); // Add some cities in the list cityList.add("London"); } } Tells compiler that Strings are expected. No compile warning on this line.

10 No Casting Needed – Boxing and Unboxing 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

11 Declaring Generic Classes and Interfaces BJ_GenericStack

To print elements of different types Before Java5 12 public class PreJava5MethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; PreJava5MethodDemo.print(integers); PreJava5MethodDemo.print(strings); } // Provide two overloaded methods public static void print(Integer[] list) { //... } public static void print(String[] list) { //... } }

To print elements of different types From Java5 with Generic Methods 13 public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; GenericMethodDemo. print(integers); GenericMethodDemo. print(strings); } public static void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

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

Can I specify the type as say ? 15 public class GenericMethodDemoF { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; GenericMethodDemo. print(integers); GenericMethodDemo. print(strings); } public static void print(F[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

Can I specify subtypes? 16 Suppose we want to restrict to Circle and Rectangle objects only in class BoundedTypeDemo

17 Bounded Generic Type 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)); } // Want to restrict to subclasses of GeometricObject public static boolean equalArea(E object1, E object2) { return object1.findArea() == object2.findArea(); }

Bounded Generic Type F See BJ_BoundedType 18

19 Raw Type and Backward Compatibility // raw type GenericStack stack = new GenericStack(); This is roughly equivalent to GenericStack stack = new GenericStack ();

20 Raw Type: Compile? Run? Safe? Why? Max.max("Welcome", 23); // 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; } // see also the code in BJ_Max around compareTo public static void main(String[] args) { System.out.println("max is " + Max.max("Welcome", 23)); }

Runtime Exception on running class Max: 21 Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at java.lang.String.compareTo(String.java:92) at Max.max(Max.java:9) at Max.main(Max.java:17)

22 Make it Safe – See class BJ_Max1 Max.max("Welcome", 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; }

23 Compilation error instead

24 Wildcards WildCardDemo1 Why wildcards are necessary? See this example. ? unbounded wildcard ? Extends T bounded wildcard ? Super T lower bound wildcard: WildCardDemo2WildCardDemo3

25

WildCardDemo1 26 public class WildCardDemo1 { public static void main(String[] args ) { GenericStack intStack = new GenericStack (); intStack.push(1); // 1 is autoboxed into new Integer(1) intStack.push(2); intStack.push(-2); System.out.println("The max number is " + max(intStack)); }

WildCardDemo1.max 27 /** Find the maximum in a stack of numbers */ public static double max(GenericStack stack) { /** intStack is an instance of GenericStack but NOT GenericStack */ double max = stack.pop().doubleValue(); // initialize max while (!stack.isEmpty()) { double value = stack.pop().doubleValue(); if (value > max) max = value; } return max; }

28 /** means any subtype of Object and associated with GenericStack */ public class WildCardDemo2 { public static void main(String[] args ) { GenericStack intStack = new GenericStack (); intStack.push(1); // 1 is autoboxed into new Integer(1) intStack.push(2); intStack.push(-2); print(intStack); System.out.println(); } // Print objects and empties the stack public static void print(GenericStack stack) { /** 1st form: ^^^ unbounded wildcard, same as ? extends Object */ while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); }

29 /** means any subtype of Object and associated with GenericStack */ public class WildCardDemo2A { public static void main(String[] args ) { GenericStack intStack = new GenericStack (); intStack.push(1); // 1 is autoboxed into new Integer(1) intStack.push(2); intStack.push(-2); print(intStack); System.out.println(); } // Print objects and empties the stack public static void print(GenericStack stack) { /** 2nd form: ^^^^^^^^^^^^^^^^^^ bounded wildcard, Number or subtype */ while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); }

WildCardDemo3 30 /** represents type T or supertype of T */ public class WildCardDemo3 { public static void main(String[] args) { GenericStack stack1 = new GenericStack (); GenericStack stack2 = new GenericStack (); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); System.out.println(); }

GenericStack 31 /** Pop each element of stack1 and push it on stack2 */ public static void add( GenericStack stack1, GenericStack stack2) { /** 3rd form ^^^^^^^^^^^ type T or super type of T. Here Object is super type of String will compile fine.*/ while (!stack1.isEmpty()) stack2.push(stack1.pop()); }

Watch out F What if we replace F GenericStack stack2) { F in line 15 of GenericStack3 by F GenericStack stack2) { F ? F Reasoning: Only Strings are in stack1, but String is subclass of Object. Must we declare stack2 as GenericStack ? 32

Answer – YES! F Change the code in WildCardDemo3A F and compile F Compiler error: F add( GenericStack, GenericStack ) in F WildCardDemo3A cannot be applied to F (GenericStack stack1, F GenericStack stack2) F Compiler usually checks syntax – pattern matching. 33

34 Generic Types and Wildcard Types The above diagram in Figure 21.6 confusing

35 Erasure and Restrictions on Generics Implementation of Generics - type erasure. - Compiler uses the generic type information to compile the code, but erases it afterwards. - Hence generic information is not available at run time. - Reason: To enable the generic code to be backward-compatible with the legacy code that uses raw types.

36 Compile Time Checking Example: -Compiler checks whether generics is used correctly for the code in (a); -Translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.

37 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, but there is only one class GenericStack loaded into the JVM.

38 Restrictions on Generics F Restriction 1: Cannot Create an Instance of a Generic Type. (i.e., new E()). F Restriction 2: Generic Array Creation is Not Allowed. (i.e., new E[100]). F Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context. F Restriction 4: Exception Classes Cannot be Generic.

Restriction 1 F Restriction 1: Cannot Create an Instance of a Generic Type. F E Object = new E(); // wrong F Reason: new E(); is run at runtime but the generic type E is not available at runtime. 39

Restriction 2 F Restriction 2: Generic Array Creation is Not Allowed. F E[] elements = new E[100]; // wrong F There is no E class F Circumvent: F E[] elements = (E[]) new Object[100]; F But warning is unavoidable 40

Restriction 2 example 41 // To instantiate an array of 10 array lists ArrayList [] list = new ArrayList [10] //wrong ArrayList [] list = (ArrayList []) new ArrayList[10]; // to circumvent // But still compiler warning

Restriction 3 F Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context. F Reason: All instance of a generic class have the same runtime class, static (class) variables and method are shared by all instances. Hence it is illegal to refer to a generic type parameter for a class in static method or field. 42

Restriction 3 F public class Teste { F public static void m(E obj1) //illegal F } –public static E obj; // illegal } 43

Restriction 4 F Restriction 4: Exception Classes Cannot be Generic. F Reason: A generic class may not extend java.util.Throwable 44

Restriction 4 45 public class MyException extends Exception { } // illegal try {... } Catch (MyException ex) {... } /* JVM would have to match the type in runtime but the type is not available at runtime. */

Review BJ_TestArrayList and BJ_GenericSort F See BJ_TestArrayListNew –Compare TestArrayList – with unchecked warnings –TestArrayListNew – no warnings needed F See BJ_GenericSortNew –Compare TestGenericSort – with unchecked warnings –And TestGenericSortNew – no warnings needed 46