1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.

Slides:



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

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Chapter 10 Introduction to Arrays
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.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
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.
Chapter 3 Introduction to Collections – Stacks Modified
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
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.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapters (ArrayList / Generic)
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Genericity Ranga Rodrigo Based on Mark Priestley's Lectures.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Generics CompSci 230 S Software Construction.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Chapter 22 Generic Programming. Chapter Goals To understand the objective of generic programming To be able to implement generic classes and methods To.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
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.
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.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter 1: Object-Oriented Programming and Java
Chapter 4: A Basic Collection Class
Chapter 20 Generic Classes and Methods
Generics.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Building Java Programs Chapter 7
Chapter 19 Generics Dr. Clincy - Lecture.
Lecture 26: Advanced List Implementation
Generic programming in Java
Generics, Lambdas, Reflections
Java Programming Language
Chapter 19 Generics.
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type

1-2 Using the Pair class /** * Illustrate the use of a generic type. */ public class GenericsEx { public static void main ( String args[] ) { Pair stringPair = new Pair ( "string", "Pair" ); Pair intPair = new Pair ( 1, 2 ); System.out.println( "intPair is: " + intPair ); System.out.println( "stringPair is: " + stringPair ); intPair.swapElements(); System.out.println("\nAfter swapping elements, intPair is " + intPair); intPair.setFirstElement( new Integer( -1 ) ); stringPair.setSecondElement( "Generic types are useful" ); System.out.println( "\nThe pairs after some resetting: " ); System.out.println( "\tintPair is: " + intPair ); System.out.println( "\tstringPair is: " + stringPair ); Integer intElement1 = intPair.getFirstElement(); String stringElement1 = stringPair.getFirstElement(); System.out.println( "\nintElement1 is " + intElement1 + " and stringElement1 is " + stringElement1 ); } intPair is: stringPair is: After swapping elements, intPair is The pairs after some resetting: intPair is: stringPair is: intElement1 is -1 and stringElement1 is string Program Output: stringPair can store a pair of String objects intPair can store a pair of Integer objects Specifying the type parameter

1-3 The Pair Class /** * A pair consists of two elements of the same type, specified by type parameter T. */ public class Pair { private T firstElement; private T secondElement; /** * Construct an instance of a Pair initialized to the given elements. e1 the first element of this pair e2 the second element of this pair NullPointerException if either e1 or e2 is null. */ public Pair( T e1, T e2 ) { if ( ( e1 == null ) || ( e2 == null ) ) throw new NullPointerException(); this.firstElement = e1; this.secondElement = e2; } /** * Return the value of the first element of this pair. the first element of this pair */ public T getFirstElement() { return this.firstElement; } /** * Swap the two elements. */ public void swapElements() { T temp = this.firstElement; this.firstElement = this.secondElement; this.secondElement = temp; }... // other stuff The generic type T can be use to declare the type of  class variables,  parameters,  return type  local variables

1-4 Generic Types and Erasure Erasure – the compiler will replace all occurrences in the class of type parameter with the upper bound of the formal type parameter The default upper bound is the class Object

1-5 Generics & Erasure: The Generic Class /** * A pair consists of two elements of the same type. This class illustrates the * definition of a generic type with type parameter T. */ public class Pair { private Object firstElement; private Object secondElement; /** * Construct an instance of a Pair initialized to the given elements. e1 the first element of this pair e2 the second element of this pair NullPointerException if either e1 or e2 is null. */ public Pair( Object e1, Object e2 ){ if ( ( e1 == null ) || ( e2 == null ) ) throw new NullPointerException(); this.firstElement = e1; this.secondElement = e2; }... // more stuff goes here After erasure, the declaration Pair intPair ; would class definition for Pair would look like this. Note that the places where T appeared have been replaced with Integer ’s upper bound, Object.

1-6 Generic & Erasure: The Client Class /** * Illustrate use of a generic type. The client class after erasure. */ public class GenericsEx { public static void main ( String args[] ) { Pair stringPair = new Pair( "string", "Pair" ); Pair intPair = new Pair( 1, 2 ); System.out.println( "intPair is: " + intPair ); System.out.println( "stringPair is: " + stringPair ); intPair.swapElements(); System.out.println("\nAfter swapping elements, intPair is " + intPair); intPair.setFirstElement( new Integer( -1 ) ); stringPair.setSecondElement( "Generic types are useful" ); System.out.println( "\nThe pairs after some resetting: " ); System.out.println( "\tintPair is: " + intPair ); System.out.println( "\tstringPair is: " + stringPair ); Integer intElement1 = (Integer)intPair.getFirstElement(); String stringElement1 = (String)stringPair.getFirstElement(); System.out.println( "\nintElement1 is " + intElement1 + " and stringElement1 is " + stringElement1 ); } Remember, the compiler takes care of doing erasure All occurrences of the formal type are removed Type casts are need to convert the Object references returned by the get methods to their respective types; the compiler does this for you!

4-7 Java Generics: Printing a Collection 10 // This method is specific to a collection of Shape objects. 11 // Note the variable type in the for loop. 12 static void printShapeCollection( Collection collection ){ 13 for ( Shape shape : collection ) 14 System.out.println( shape ); 15 } Collection shapes = new BasicCollection (); 27 shapes.add( new Circle( 5.0 ) ); 28 shapes.add( new Rectangle( 4.5, 21.2 ) ); 29 shapes.add( new Cube( ) ); 30 System.out.printf( “From printShapeCollection( shapes )\n”); 31 printShapeCollection( shapes ); Collection circles = new BasicCollection (); 34 circles.add( new Circle( 5.0 ) ); 35 circles.add( new Circle( 15.0 ) ); 36 circles.add( new Circle( 25.0 ) ); 37 //printShapeCollection( circles ); // ERROR! Goal: Create a method to print all the elements in a collection. Problem: How to express the type in the parameter list? Collection ) in UnboundedWildcardEx cannot be applied to (java.util.Collection ) Lesson: While a Circle “is a kind of” Shape, a Collection is NOT “a kind of” Collection ! Think of it this way. If Collection “is a kind of” Collection, then anything you can do to Collection, you should be able to also do to Collection, but I can add a Rectangle to Collection, but not to Collection !

4-8 The Unbounded Wildcard ‘?’ 18 // The most general print method. It will print collections of 19 // any kind of type. Note the variable type in the for loop. 20 static void printAnyCollection( Collection collection ){ 21 for ( Object element : collection ) 22 System.out.println( element ); 23 } So, what to do? We need more flexibility in the type parameter. That is, instead of specifying the exact type of the collection, we want to accept a collection storing a family of types. Java’s solution is the type wildcard, ?, which, because it matches anything, is called an unbounded wildcard. More formally, ? is said to be an “unknown type”; thus Collection is a “collection of unknown type.”

4-9 Another Example: Collection.containsAll() 1 public boolean containsAll( Collection c ) { 2 Iterator e = c.iterator(); 3 while ( e.hasNext() ) 4 // does this collection contain the 5 // next element from c? 6 if( !contains( e.next() ) ) 7 // nope, c has an element we don’t have 8 return false; 9 return true; // yep, we have all the elements c has 10 } Note that the element type of the Collection c must match the element type of the Iterator over c.

4-10 Bounded Wildcards There will be times when we don’t want the broad inclusiveness of the unbounded wildcard and would prefer to put a bound on the family of types accepted. The bounded wildcard does this. Example: The addAll() method from Collection. Here is the class header for AbstractCollection public abstract class AbstractCollection implements Collection { This means we can store elements of type E or any of E’s subclasses in the collection.

4-11 Bounded Wildcard What should be the parameter for addAll() ? Too restrictive. This would preclude adding a Collection to a Collection or a Collection to a Collection. public Boolean addAll(Collection c) 1 st attempt public abstract class AbstractCollection implements Collection { Not restrictive enough. Would let you try to add a Collection to a Collection. public Boolean addAll(Collection c) 2 nd attempt

4-12 Bounded Wildcard: What we need is a flexible mechanism that will allow us to specify a family of types constrained by some “upper bound” on the type family. Java’s bounded wildcard does just this. 1 // method from AbstractCollection 2 public boolean addAll(Collection c) { 3 boolean modified = false; 4 Iterator e = c.iterator(); 5 6 while ( e.hasNext() ) { 7 if ( add( e.next() ) ) 8 modified = true; 9 } 10 return modified; 11 } The bounded wildcard in the parameter type means that the Collection type is unknown, but is bounded by type E. That is, the element type of c must be E or one of its subclasses.

Collection reverseCopy( Iterator source ) { 19 LinkedList theCopy = new LinkedList (); 20 while ( source.hasNext() ) 21 theCopy.addFirst( source.next() ); // add at front of list 22 return theCopy; 23 } Collection reverseCopy( Collection source ) { 26 LinkedList theCopy = new LinkedList (); 27 for ( E element : source ) 28 theCopy.addFirst( element ); // add at front of list 29 return theCopy; 30 } Generic Methods: Two Examples 33 Collection pets = new BasicCollection (); 40 Collection petsCopy = copy( pets ); 45 petsCopy = reverseCopy( pets ); 50 petsCopy = reverseCopy( petsCopy.iterator() );