Generics. Writing typed checked generic code There are many instances where the type of the object is irrelevant : –The construction of data structures.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Java Review Interface, Casting, Generics, Iterator.
Generics and the ArrayList Class
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Abstract Data Types. Typical operations on data  Add data to a data collection  Remove data from a data collection  Ask questions about the data in.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java 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.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Games and Simulations O-O Programming in Java The Walker School
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
OOP Languages: Java vs C++
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
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.
ArrayList, Multidimensional Arrays
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Working with arrays (we will use an array of double as example)
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
CSI 3125, Preliminaries, page 1 Compiling the Program.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION GENERICS/PARAMETRIC POLYMORPHISM Autumn 2011 We We Abstraction.
©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.
 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:
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
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.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Simple algorithms on an array - compute sum and min.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
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.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
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.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
(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.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Modern Programming Tools And Techniques-I
7. Inheritance and Polymorphism
Generics (Parametric Polymorphism)
Java Programming Language
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
From C++ to Java Java history: Oak, toaster-ovens, internet language, panacea What it is O-O language, not a hybrid (cf. C++) compiled to byte-code, executed.
slides created by Marty Stepp
Chapter 5 Classes.
Presentation transcript:

Generics

Writing typed checked generic code There are many instances where the type of the object is irrelevant : –The construction of data structures. –The specification and implementation of methods.

Generic data structures Containers are and ought to be independent of the type of their entries. –A list specification and implementation is the same regardless of the type of its entries.

Generic operations There are many methods whose algorithm is and ought to be independent of the type of its parameters: –Swapping –Reversing a list –Length –Spliting a list –Concatenating two lists –Sorting

Java’s old solution For containers: –Use Object as the generic type. This solution has only negative consequences: –Elements added to a container cannot be typed checked for its true type: i.e. we loose type checking. –Client of containers must coerce at run-time to the expected type: instanceof is an expensive operation. Client may coerce to the incorrect type. Without use of instanceof client may run into run-time errors. –For production of safe code programmers must define abstract containers based on Object and subclass it for the expected type of container’s entries: It breaks Liskov’s substitutability principle. Client is forced to write and maintain repeated code It leads to class explosion when container is subclassed.

Java’s new solution: Generics. What are generics? Generics allows you to abstract over types. Specifically you can specify parameters whose values are types. Example: The only difference between the different XXXList is the type of the entries. –Specify the list using type as a parameter. –Implement the list using the parameter wherever you need a specific type. –When you need a specific list (a list of students): Instantiate the List matching the parameter type with Student.

Java’s generic syntax public class List { … public void add(Entry element) {…} public Entry get(int index){.. } … private Entry[] elements; } Entry in angular brackets represents a type variable, to be matched by an existing class when the generic class is instantiated.

Generic List instantation List studentList = new List (1,20); Matches the type parameter throughout the class implementation Matches the List constructor’s parameters

import java.util.Vector; class DynamicList { public DynamicList() { elements = new Vector (); } public boolean isEmpty(){ return elements.size() == 0; } public Entry get(int i){ return elements.get(i); } public int indexOf( Entry entry){ return elements.indexOf(entry); } public void append (Entry entry){ elements.add(entry); }

public void add(int i, Entry entry){ elements.add(i, entry); } public void remove(int i){ elements.removeElementAt(i); } public int size() { return elements.size(); } public void set ( int i, Entry entry){ elements.set(i,entry); } private Vector elements; } DynamicList studentList = new DynamicList ( ); //constructors arguments if any,

Generic methods Using the Java’s generic extension we can also write methods whose algorithm does not depend on explicit types: –To swap two entries in an array. void swap(Element[] a, int i1, int i2){ Element temp = a[i1]; a[i1] = a[i2]; a[i2] = temp; } An invocation: swap(integersTable, 3, 7);

More examples of generic functions Interface Function { B value(A arg); } Interface Ntuple { Ntuple map( Function f); } Ntuple nti = ….; nti.map( new Function { Integer value(Integer i){ return new Integer(i.intValue()*2); } );

Java’s generic Classes Abstract classes Interfaces methods

Java’s generic trade-offs Positive: –The way to catch type errors up front. –Code is more readable. –Client does not have to coerce. –Totally compatible with current Java Negative: –The choice of implementation of generic code may produce unexpected warning errors. Cannot overload based on different instantiations of same generic type.

How can I start using generics? For home use follow the link to: download jdk1.5 extensions (zip file) README file instructs you for setup and compilation of generic code Need to set two environment variables use the javac version provided to compile generic code. The usual javac will not compile it. The command to run the interpreter ( java ) will also need to be changed to use new generic libraries.

Java generics in the dept To run the compiler from the department network, set the environment variables J2SE14 and JSR14DISTR. export J2SE14=/usr/java export JSR14DISTR=/home/c /Utilities/adding_generics-2_2-ea and run the scripts javac and java from / home/c /Utilities/adding_generics-2_2-ea/scripts to compile and execute. To simplify all the above, two scripts to run the compiler and interpreter, javac1.5 and java1.5, are available in /home/c /scripts. You can simply copy these scripts to your home directory and use them to compile and run. For example, $ ~/javac1.5 foo.java $ ~/java1.5 foo