Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.

Slides:



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

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.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
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.
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)
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
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 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.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Java Generics.
Methods CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
CSC 243 – Java Programming, Spring 2013 March 12, 2013 Week 7, Generics.
CMSC 341 Inheritance and the Collection classes. 8/03/2007 UMBC CMSC 341 Java 3 2 Inheritance in Java Inheritance is implemented using the keyword extends.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
 2005 Pearson Education, Inc. All rights reserved Generics.
Conditions CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Generics. What is Generics Collections can store Objects of any Type Generics restricts the Objects to be put in a collection Generics ease identification.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Introduction to Generics
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Serialization CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
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:
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Networking Code CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
 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.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Reading Parameters CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D.
Sixth Lecture ArrayList Abstract Class and Interface
CIS265/506 Cleveland State University – Prof. Victor Matos
John Hurley Cal State LA
Chapter 20 Generic Classes and Methods
Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
Chapter 19 Generics.
Chapter 21 Generics.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Exception Handling Contents
Chapter 21 Generics.
Chapter 19 Generics.
Subtype Substitution Principle
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L

Outline USC CSCI 201L2/18 ▪G▪Generics ›G›Generic Classes ›G›Generic Methods ▪P▪Program

Generics Overview ▪Generics were introduced in Java version 5.0 in 2004 ▪Generics allow you to parameterize types ›This is similar to templates in C++ ▪A class or method can be defined with generic types that the compiler can replace with concrete types ▪Generics allow type errors to be detected at compile time rather than runtime ›A generic class or method allows you to specify allowable types of objects that the class or method can use, and if you attempt to use an incompatible type, a compiler error will occur ›Before generics, methods that took multiple types had to take a parent type (usually Object), but then any variable that inherits from that class could be passed in, not just a subset of them, potentially causing a runtime error 1 public interface Comparable {1 public interface Comparable { 2 public int compareTo(Object o);2 public int compareTo(T o);3...4 } USC CSCI 201L3/18 Generics – Generic Classes

Generic Instantiation ▪To create a class or interface that takes a generic, include an identifier (by convention, a single capital letter) in angle brackets immediately following the name of the class or interface ›Use that identifier in any variable declaration or return type in the class ›When you create an instance of that class, you will need to parameterize the class with a concrete class to use in place of that generic Note: You must use a concrete class and not a primitive data type or abstract class 1 public class Test { 2 3 public void print(T t) { 4 System.out.println(t); 5 } 6 7 public static void main(String args[]) { 8 Test t = new Test (); 9 t.print("Hello CSCI201"); 10 } 11 } USC CSCI 201L4/18 Generics – Generic Classes

Using Generics ▪Does this code compile? 1 public class Test { 2 3 public void print(T t) { 4 System.out.println(t); 5 } 6 7 public static void main(String args[]) { 8 Test t = new Test (); 9 t.print(33); 10 } 11 } USC CSCI 201L5/18 Generics – Generic Classes

Generics with ArrayList ▪The generic passed into an ArrayList must be an object, no primitive types ›Casting is allowed though 1 import java.util.ArrayList; 2 3 public class Test { 4 5 public static void main(String args[]) { 6 ArrayList arr = new ArrayList (); 7 arr.add(3); 8 arr.add(new Integer(4)); 9 arr.add("5"); 10 int num = arr.get(0); 11 System.out.println("num = " + num); 12 } 13 } USC CSCI 201L6/18 Generics – Generic Classes

Generic Stack 1 import java.util.ArrayList; 2 public class Test { 3 private ArrayList list = new ArrayList (); 4 5 public int getSize() { 6 return list.size(); 7 } 8 public E peek() { 9 return list.get(getSize()-1); 10 } 11 public void push(E o) { 12 list.add(o); 13 } 14 public E pop() { 15 E o = list.get(getSize()-1); 16 list.remove(getSize()-1); 17 return o; 18 } USC CSCI 201L7/18 Generics – Generic Classes 19 public boolean isEmpty() { 20 return list.isEmpty(); 21 } 22 public static void main(String [] args) { 23 Test stack1 = new Test (); 24 stack1.push("CSCI103"); 25 stack1.push("CSCI104"); 26 stack1.push("CSCI201"); 27 Test stack2 = new Test (); 28 stack2.push(103); 29 stack2.push(104); 30 stack2.push(201); 31 } 32 }

Multiple Generics 1 import java.util.ArrayList; 2 public class GenericStack { 3 private ArrayList list = new ArrayList (); 4 5 public int getSize() { 6 return list.size(); 7 } 8 public E peek() { 9 return list.get(getSize()-1); 10 } 11 public void push(E o) { 12 list.add(o); 13 } 14 public E pop() { 15 E o = list.get(getSize()-1); 16 list.remove(getSize()-1); 17 return o; 18 } USC CSCI 201L8/18 Generics – Generic Classes 19 public boolean isEmpty() { 20 return list.isEmpty(); 21 } 22 public void print(F f) { 23 System.out.println(f); 24 } 25 public static void main(String [] args) { 26 GenericStack stack1 = new GenericStack (); 27 stack1.push("CSCI103"); 28 stack1.push("CSCI104"); 29 stack1.push("CSCI201"); 30 stack1.print(3.5); 31 GenericStack stack2 = new GenericStack (); 32 stack2.push(103); 33 stack2.push(104); 34 stack2.push(201); 35 stack2.print("Hello CSCI201"); 36 } 37 }

Generic Methods ▪The class does not need to be parameterized if you are only needing a static method within the class to be parameterized 1 public class Test { 2 public static void print(T [] list) { 3 for (int i=0; i < list.length; i++) 4 System.out.print(list[i] + " "); 5 System.out.println(); 6 } 7 8 public static void main(String[] args ) { 9 Integer[] integers = {1, 2, 3, 4, 5}; 10 String[] strings = {"London", "Paris", "New York", "Austin"}; Test. print(integers); 13 Test. print(strings); 14 } 15 } USC CSCI 201L9/18 Generics - Generic Methods

Bounded Generics ▪You can specify that you want a generic type to be a subtype of another type 1 import java.io.BufferedReader; 2 import java.io.FileReader; 3 import java.io.IOException; 4 import java.io.Reader; 5 6 public class Test { 7 public static void openFile(T t) throws IOException { 8 BufferedReader br = new BufferedReader(t); 9 String line = br.readLine(); 10 } 11 public static void main(String[] args ) { 12 try { 13 Test. openFile(new FileReader(args[0])); 14 } catch (IOException ioe) { 15 System.out.println("exception: " + ioe.getMessage()); 16 } 17 } } USC CSCI 201L10/18 Generics - Generic Methods

Missing Generics ▪If a class or method is parameterized and you leave off the generic instantiation, the class or method will be parameterized with the Object class ›This is why you cannot use primitive types in generic instantiations ›The following two lines are equivalent ›This keeps backwards compatibility with previous versions of Java before serialization existed 1Vector v = new Vector(); 2Vector v = new Vector (); USC CSCI 201L11/18 Generics - Generic Methods

Subclass Generics ▪Does the following code compile? 1 public class WildCardDemo { 2 public static void main(String[] args ) { 3 GenericStack intStack = new GenericStack (); 4 intStack.push(1); // 1 is autoboxed into new Integer(1) 5 intStack.push(2); 6 intStack.push(-2); 7 System.out.print("The max number is " + max(intStack)); 8 } 9 public static double max(GenericStack stack) { 10 double max = stack.pop().doubleValue(); // Initialize max 11 while (!stack.isEmpty()) { 12 double value = stack.pop().doubleValue(); 13 if (value > max) { 14 max = value; 15 } 16 } 17 return max; 18 } 19 } USC CSCI 201L12/18 Generics - Generic Methods

Wildcard Generics ▪There are three types of wildcard generics ›Unbounded wildcard – written either as ? or ? extends Object ›Bounded wildcard – written as ? extends T represents T or an unknown subtype of T ›Lower-bound wildcard – written as ? super T denotes T or an unknown supertype of T ▪Wildcard generics can be used on parameterized classes and parameterized methods USC CSCI 201L13/18 Generics - Generic Methods

Subclass Generics ▪This code now compiles 1 public class WildCardDemo { 2 public static void main(String[] args ) { 3 GenericStack intStack = new GenericStack (); 4 intStack.push(1); // 1 is autoboxed into new Integer(1) 5 intStack.push(2); 6 intStack.push(-2); 7 System.out.print("The max number is " + max(intStack)); 8 } 9 public static double max(GenericStack stack) { 10 double max = stack.pop().doubleValue(); // Initialize max 11 while (!stack.isEmpty()) { 12 double value = stack.pop().doubleValue(); 13 if (value > max) { 14 max = value; 15 } 16 } 17 return max; 18 } 19 } USC CSCI 201L14/18 Generics - Generic Methods

Superclass Generics ▪Does the following code compile? 1 public class WildCardDemo3 { 2 public static void main(String[] args) { 3 GenericStack stack1 = new GenericStack (); 4 GenericStack stack2 = new GenericStack (); 5 stack2.push("Java"); 6 stack2.push(2); 7 stack1.push("Sun"); 8 add(stack1, stack2); 9 } public static void add(GenericStack s1, GenericStack s2) { 12 while (!s1.isEmpty()) { 13 s2.push(s1.pop()); 14 } 15 } 16 } USC CSCI 201L15/18 Generics - Generic Methods

Superclass Generics (cont.) ▪The following code now compiles 1 public class WildCardDemo3 { 2 public static void main(String[] args) { 3 GenericStack stack1 = new GenericStack (); 4 GenericStack stack2 = new GenericStack (); 5 stack2.push("Java"); 6 stack2.push(2); 7 stack1.push("Sun"); 8 add(stack1, stack2); 9 } public static void add(GenericStack s1, GenericStack s2) { 12 while (!s1.isEmpty()) { 13 s2.push(s1.pop()); 14 } 15 } 16 } USC CSCI 201L16/18 Generics - Generic Methods

Outline USC CSCI 201L17/18 ▪G▪Generics ›G›Generic Classes ›G›Generic Methods ▪P▪Program

Program ▪Create a sorting program that allows any type of number to be taken as a parameter and it will still sort the array. The user should be prompted to enter the type of variables he wants. USC CSCI 201L18/18 Program (i) Integer (f) Float (d) Double What type of array would you like to sort? f Original array: 3.4, 1.2, 5.2, 6.3, 2.9 Sorted array: 1.2, 2.9, 3.4, 5.2, 6.3