1 Generics Chapter 21 Liang, Introduction to Java Programming.

Slides:



Advertisements
Similar presentations
Generics and the ArrayList Class
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.
Road Map Introduction to object oriented programming. Classes
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) Generics.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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,
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Generics.
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.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Chapters (ArrayList / Generic)
Chapter 18 Java Collections Framework
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Introduction to Generics
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CIS 270—Application Development II Chapter 18-Generics.
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
©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:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
CMSC 202 ArrayList Aug 9, 2007.
Chapter VII: Arrays.
Sixth Lecture ArrayList Abstract Class and Interface
CIS265/506 Cleveland State University – Prof. Victor Matos
Java Generics.
Chapter 20 Generic Classes and Methods
COP 3503 FALL 2012 Shayan Javed Lecture 8
TCSS 143, Autumn 2004 Lecture Notes
Chapter 19 Generics Dr. Clincy - Lecture.
Can store many of the same kind of data together
Chapter 19 Generics.
Chapter 21 Generics.
CS2013 Lecture 3 John Hurley Cal State LA.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Java Programming Language
slides created by Alyssa Harding
Review: libraries and packages
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

1 Generics Chapter 21 Liang, Introduction to Java Programming

2 Place these programs and their classes from folder Generics on the desktop GenericMethodDemo GenericClass.java GenericClass2.java Liang, Introduction to Java Programming

3 Objectives F To use generic classes and interfaces from the API F To declare generic classes and interfaces F To understand why generic types can improve reliability and robustness F To declare and use generic methods F To know wildcard types and understand why they are necessary Liang, Introduction to Java Programming

4 Introduction F Generic is the capability to parameterize types F You can declare a generic type in a class, interface, or method F You can specify a concrete type when using the generic class, interface or methods F Generic types can improve readability, reliability and robustness for the program F The new JDK 1.5 generic types provide a mechanism that supports type checking at compile time Liang, Introduction to Java Programming

5 Generic Type Generic Instantiation Runtime error Compile error b) Improves reliability

Liang, Introduction to Java Programming 6 Generics contd. The prior slide declares that c is a reference variable whose type is Comparable in JDK 1.5 and invokes the compareTo method to compare a Date object with a string. The code has a compile error, because the argument passed to the compareTo method must be of the Date type. Since the errors can be detected at compile time rather than at runtime. The generic type makes the program more reliable.

Liang, Introduction to Java Programming 7 Generics contd. Caution: Generic type must be reference types. You cannot substitute a generic type with a primitive such as int, double, or char, float, etc. However, you can use wrapper classes such as Integer, Double, Character, etc instead. Note: Occasionally, a generic class may have more than one parameter. In this case, place the parameters together inside the angle brackets, separated by commas such as

8 The ArrayList Class in JDK1.5 is now a Generic class Java.util.ArrayList +ArrayList() +add(E o): booleanaddE +add(int index, E element) : voidadd +clear() : void clear +clone() : Object clone +get(int index) : Eget +indexOf(Object elem) : intindexOfObject +set(int index, E element) : Eset Liang, Introduction to Java Programming

99 ArrayList The ArrayList class is a generic class. You can form array lists that collect different types, such as ArrayList, ArrayList and so on Liang, Introduction to Java Programming

10 Create an ArrayList F Create a list for a String ArrayList list = new ArrayList (); F Add only strings to the list list.add(“red”); F The following statement will generate an error list.add(new Integer(1)); because list can only contain strings Liang, Introduction to Java Programming

11 No Casting Needed Casting is not needed to retrieve a value from a list with a specified element type because the compilier already knows the element type: 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 Liang, Introduction to Java Programming

12 Implementing Generic Classes We need to give names to the type variables. It is consider good form to give short uppercase names for type variables, such as the following: Type Variable NameMeaning EElement type in a collection KKey type in a map VValue type in a map TGeneral type S,UAdditional general types Liang, Introduction to Java Programming

13 Syntax for Defining a Generic Class accessSpecifier class GenericClassName <TypeVariable1, TypeVariable2,…> { constructors methods fields } Liang, Introduction to Java Programming

14 Creating a Generic Class public class GenericClass { private E[] element; //an array to store elements private int size; //default constructor public GenericClass() { element = (E[]) new Object[10];//set physical size of 10 size = 0; } Liang, Introduction to Java Programming

15 Important Facts It is important to note that a generic class is shared by all its instances (objects) 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. Liang, Introduction to Java Programming

16 Generic methods public static void print (E[] list) { for (int i =0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } In main: Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York" }; ClassName. print(integers); ClassName. print(strings); Liang, Introduction to Java Programming

17 Example F Run the program : GenericClass.java Liang, Introduction to Java Programming

18 Wild Card F To create a generic method, a wild card must be used F The wild card argument is specified by the ? F The wild card specify the unknown type F Run program GenericClass2.java Liang, Introduction to Java Programming