CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.

Slides:



Advertisements
Similar presentations
Review Generics and the ArrayList Class
Advertisements

Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
Generics and the ArrayList Class
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 23 : Generics King Fahd University of Petroleum & Minerals College of Computer Science.
Generics and The ArrayList Class
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
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.
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 and Type Safety Recitation – 4/24/2009 CS 180 Department of Computer Science, Purdue University.
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.
Static Class Members Wrapper Classes Autoboxing Unboxing.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
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.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Polymorphism & Interfaces
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
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.
The Java Collections Framework (JCF) Introduction and review 1.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Types in programming languages1 What are types, and why do we need them?
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.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
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.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Typecasting References Computer Science 3 Gerb Reference: Objective: Understand how to use the Object class in Java in the context of ArrayLists.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
The ArrayList Data Structure Standard Arrays at High Speed!
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.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Java Generics.
Sixth Lecture ArrayList Abstract Class and Interface
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Java Primer 1: Types, Classes and Operators
Chapter 20 Generic Classes and Methods
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generics 27-Nov-18.
Arrays and Collections
Java Programming Language
Review: libraries and packages
Generics 2-May-19.
Chapter 19 Generics.
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Presentation transcript:

CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes

CS-2851 Dr. Mark L. Hornick 2 ArrayList vs. ArrayList ( or LinkedList vs. LinkedList ) JDK 1.4 (deprecated): To declare an ArrayList that can contain any datatype: ArrayList someList; You’ll get a warning if you do this (not an error) – don’t use this approach! JDK 1.5 and later: To declare an ArrayList that can contain only Double’s: ArrayList salaryList;

CS-2851 Dr. Mark L. Hornick 3 Generics – new to J2SE 5.0/JDK 1.5 Eclipse must be configured to use JDK 1.5 or 1.6 you should have 1.6 on your PC

CS-2851 Dr. Mark L. Hornick 4 Generic ArrayList ArrayList salaryList = new ArrayList (); E specifies the specific type of data that the ArrayList can manage You must substitute a class name for E This creates an instance, salaryList, of the ArrayList collection class. The elements in salaryList must be (references to) Doubles. Q: Why do we have to use ArrayList ? Can’t we just use ArrayList ? A: No. The generic type E must represent a class, not a primitive. Double is a wrapper class that just represents a double primitive.

CS-2851 Dr. Mark L. Hornick 5 Wrapper-to-primitive type conversion is done automatically through boxing and unboxing Example: You want to insert a double value into an ArrayList at index 30: salaryList.add(30, ); // works!! This is called boxing: The automatic conversion of a primitive double value ( ) to the appropriate Double wrapper object To retrieve the value, no explicit cast is needed: double pay = /*(double)*/ salaryList.get(30); This is because although the get() method returns a Double, a Double can be automatically converted to a double primitive type. This is called unboxing.

CS-2851 Dr. Mark L. Hornick 6 Datatype parameter placeholders appear in the definition of classes and interfaces public class ArrayList {…} E (for “Element”) is a type parameter E is not a keyword, just a placeholder The letter T is also used as a placeholder But you can use any (non-keyword) placeholder name E and T are commonly-used symbols Generics allow you to create a class template that can use different types of objects when instantiated

Writing your own generic class Consider a class that deals with ints public class Maxinator { public int getMaxValue(int a, int b) { int max=0; int result = a-b; if( result > 0 ) max=a; else if( result < 0 ) max=b; else // a and b are the same max=a; return max; } CS-2851 Dr. Mark L. Hornick 7

Next, replace int with a generic placeholder Typically, we use the letter E: public class Maxinator { public E printMaxValue(E a, E b) { E max=0; E result = a-b; // any issues here?? if( result > 0 ) max=a; else if( result < 0 ) max=b; else // a and b are the same max=a; return max; } CS-2851 Dr. Mark L. Hornick 8

The compiler doesn’t “know” what datatype E represents However, we can specify that E must be a subclass of Number (the superclass of Double, Integer, Float, etc). public class Maxinator { public printMaxValue(E a, E b) { int max=0; int result = a.intValue() – b.intValue(); // all Numbers support the intValue() method if( result > 0 ) max=a; else if( result < 0 ) max=b; else // a and b are the same max=a; return max; } CS-2851 Dr. Mark L. Hornick 9

So far, we have limited our Maxinator class to handle subtypes of Number What if we wanted to allow it to compare other datatypes, like Strings and Students?? We need another way to compare the objects, regardless of the datatype represented by E CS-2851 Dr. Mark L. Hornick 10 The Comparable interface is the key to doing this for any datatype represented by E.

The Comparable interface in the java.lang package This interface defines a single method: int compareTo(E o) // returns -1, 0, or 1 This method compares this object (the one invoking the compareTo() method) to another object of the same datatype (the object represented by o) Many datatypes already implement Comparable: String msg = “Hello”; int result = msg.compareTo(“hello”); // returns 1 Double x = 3.0; result = x.compareTo(4.0); // returns -1 result = x.compareTo(3.0); // returns 0 CS-2851 Dr. Mark L. Hornick 11

We can specify that the class represented by E must implement the Comparable interface Any class E that implements Comparable contains the compareTo() method!! public class Maxinator > { public printMaxValue(E a, E b) { int max=0; int result = a.compareTo(b); // returns -1, 0, or 1 if( result > 0 ) max=a; else if( result < 0 ) max=b; else // a and b are the same max=a; return max; } CS-2851 Dr. Mark L. Hornick 12

Fall 2004CS-183 Dr. Mark L. Hornick 13 Writing Generic Classes 1. Write the basic class using a simple type e.g. int 2. Test it using a test program Make sure it works 3. Replace the simple type identifier with E Or other generic type name 4. Add the generic suffix public class MyGenericClass

Fall 2004CS-183 Dr. Mark L. Hornick 14 Using Generic Classes 1. Declare the specific class using a specific type MyGenericClass 2. Test it using a test program Make sure it still works All specific types (Integer, String, Student) must support the same methods, (e.g. compareTo())