Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.

Slides:



Advertisements
Similar presentations
New features in JDK 1.5 Can these new and complex features simplify Java development?
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Wildcards in the Java™ Programming Language Neal Gafter with thanks to Mads Torgersen, University of Aarhus.
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.
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.
Generic programming in Java
Java Generics.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Generic Programming Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 The Problem Assume we have a nice Stack implementation. Our stack receives.
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.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
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.
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.
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.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
Types in programming languages1 What are types, and why do we need them?
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
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.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
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.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CS2 Module 26 Category: OO Concepts Topic: Interfaces Objectives –Interfaces.
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.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
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.
More on Java Generics Multiple Generic Types Bounded Generic Types
Generic(Parameterized ) Types
Chapter 20 Generic Classes and Methods
Generics, Lambdas, Reflections
Generics (Parametric Polymorphism)
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generics 27-Nov-18.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Review: libraries and packages
Generics 2-May-19.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

Generics1 Parametrized classes and methods

Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of types. –They have 1 or more formal type parameters –Using a generic you specify an actual type Also known as “parametrized types” –Or types with “holes”

Generics3 No more type casts Before generics –List myList = new ArrayList(); –myList.add(“Anders”); –… –String str = (String)myList.get(0); –Type casts are generally considered bad since they may fail at runtime If you add something that is not a string –myList.add(new Integer(56)); After generics –List = new ArrayList (); –myList.add(“Anders”); –… –String str = myList.get(0); –myList is not typed To String in this case –We don’t need type casting. –We cannot add anything but Strings myList.add(56); –Does not compile

Generics4 Benefits of generics Making code better –Runtime: No ClassCastException –Compile time: Compiler discovers wrong uses of types. Making code more flexible –Generic classes can be instantiated with different types.

Generics5 Defining and using your own generic class Definition public class Catalog { List catalog = new ArrayList (); public boolean add(T element) { catalog.add(element); } Usage Catalog bc = new Catalog (); Catalog bookCatalog = new Catalog ();

Generics6 Erasure At compile-time all the types are checked and removed (erased) from the class file. –What is left is called the “raw type” –The class file has no knowledge of the types. –Example Catalog is “erased” to Catalog

Generics7 Erasure (2) Types are checked and removed (erased) –No generics in the JVM. All instances of a generics class has the same run-time class List list = new ArrayList (); System.out.println("list type: " + list.getClass()); Writes ArrayList, nothing said about String. if (list instanceof ArrayList ) … Illegal, since is not present at run-time if (list instanceof ArrayList) … Legal

Generics8 Relationships among generics Object is a super type of String. ArrayList is not a super type of ArrayList –Object and String are erased at compile time. –Runtime system has no knowledge of the types. –Example

Generics9 Raw types The raw types are the generic types, but without a specified actual type –ArrayList, Collection, Catalog Collection is “equal” to Collection –but not Collection Collection c = method.returnsCollOfSomething –Generates “unchecked warning”

Generics10 An example: Using raw types to break “security” public String loophole(Integer x) { List ys = new LinkedList (); List xs = ys; xs.add(x); // Compile time: warning: unchecked call return ys.get(0); } We used xs as an oldfashioned (untyped) alias to ys. Using xs we were able to insert an Integer into ys. Generally –Don’t ignore warnings. –Avoid untyped collections. From: Gilad Bracha: Generics in the Java Programming Language, page 12

Generics11 Wildcard types Yet another feature to solve the problems with relationships among generics. New syntax: ? Example – htmlhttp://java.sun.com/docs/books/tutorial/java/javaOO/genwildcard. html –MyClass MyClass of any type Example –Boolean java.util.Collection.containsAll(Collection c) –

Generics12 Wild card types with upper bounds Sometimes the types cannot be chosen completely free –We have to make sure that the type has certain features Example –Java.util.Collection.addAll(Collection c) mlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.ht ml Can use any collection of types that extends E (which is the element type of this Collection The type is said to have an “upper bound” (in the class hierarchy) –In this case E

Generics13 Generics methods Methods (static and non-static) can be generic Syntax – T method(T element) { …} Most often with static methods Example – List Collections.synchronizedList(List list) mlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.ht ml

Generics14 Wild cards with lower bounds Most often used with generic methods Examples from java.util.Collections –static void fill(List list, T obj) Replaces all of the elements of the specified list with the specified element. T is the type of the new object List must have elements which are super types of T –T is a lower bound in the object hierarchy Example –List list; –… –Collections.fill(list, new JButton());

Generics15 Bound wildcards ? Extends Tupper bound –Unknown type that is a subtype of T Or T itself ? super Tlower bound –Unknown type that is a super type of T Or T itself

Generics16 Comparing and sorting The class java.util.Collections has static methods for ordering elements in lists – > void sort(List list)ComparableList – void sort(List list, Comparator c)ListComparator –This is a lot of syntax! –First sort method orders elements according to the natural order int 1,2,3,4, etc. String a, b, c, etc. –Second sort method orders elements according to the specified comparator A comparator compares 2 elements and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Generics17 Using generics with legacy code Legacy code means old code –In this case code written prior to Java 5.0 is considered old How do you deal with legacy classes that don’t use generics (but ought to)? –Examples Generics – legacycode.Cat Compiler sends you warnings –… uses unchecked or unsafe operations When you call methods on a raw type –… unchecked cast When you cast from raw to generic type. –You may have to live with such warnings Or change the legacy code

Generics18 Other programming languages C++ templates –No erasures (no wildcards): Code bloat –Code is expanded

Generics19 References Sun Microsystems The Java Tutorial –Generics –Easy introduction to generics. Gilad Bracha Generics in the Java Programming Language, Sun Microsystems 2004 – –Also known as the ”Generics Tutorial” –Through introduction to generics.