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.

Slides:



Advertisements
Similar presentations
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 17: Type Conversions,
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Generics and the ArrayList Class
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Java Generics.
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
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.
Lists Discussion F. Generics Tutorial (Ref: Gilad Baracha) ● Auto Boxing ● Erasure ● Sub Classes ● Unchecked Type cast ● Bounded Wildcards.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
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.
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.
Java Generics.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
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.
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.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
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.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CMSC 330: Organization of Programming Languages Java Generics.
Java 1.5 Generics Amr Ali Software Engineer, IBM-Egypt EG-JUG.
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.
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
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.
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.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
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.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
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.
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.
Modern Programming Tools And Techniques-I
More on Java Generics Multiple Generic Types Bounded Generic Types
Chapter 20 Generic Classes and Methods
Java Generics.
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Java Programming Language
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

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 and safer. ➲ Reduces the runtime cast exceptions. ➲ Increase readability and robustness.

Comparison In JDK1.4 List myIntList = new LinkedList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next(); In JDK1.5 List myIntList = new LinkedList (); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();

Defining Simple Generics The definition of list and Iterator in java.util public interface List { void add(E x); Iterator iterator(); } public interface Iterator { E next(); boolean hasNext(); }

Generics ➲ The E in the angle Bracket is the formal parameter. ➲ This E gets replaced with the respective actual parameter in the invocation of the method. ➲ The generic type declaration complied only once and turned into single class file. ➲ Note on naming convention :Recommended to use single characters and avoid lower case.

Generics and Sub typing Consider the code snippet List list_str = new ArrayList (); //1 List list_obj = ls; //2 list_obj.add(new Object()); // 3 String s = list_str.get(0); // 4: assigning an Object to a String! Useful to consider more flexible generic types.

WildCards Consider the routine to print all elements in a collection older version void printCollection(Collection c) { Iterator i = c.iterator(); for (k = 0; k < c.size(); k++) { System.out.println(i.next()); }

WildCards Same routine using JDK1.5 void printCollection(Collection c) { for (Object e : c) { System.out.println(e); }

WildCards WildCard invocation void printCollection(Collection c) { for (Object e : c) { System.out.println(e); }

WildCards Unsafe to Add objects using add() Collection c = new ArrayList (); c.add(new Object()); // compile time error We can use get() method.

Bounded Wildcards Suppose we have simple application that can draw shapes such as rectangles and circles. Public abstract class Shape{ public abstract void draw(Canvas C); } public class Circle extends Shape {..... } public class Rectangle extends Shape {..... }

Bounded WildCards These class are drawn on a canvas public class Canvas { public void draw(Shape s){ s.draw(this);} } Canvas with drawAll() function public void drawAll(List shapes) { for (Shape s: shapes) { s.draw(this); } This DrawAll() can only be used on a list of type SHAPE.

Bounded WildCards The DrawAll() excepting a list of anykind public void drawAll(List shapes) {... } This function will accept any subclass of Shape. Price for flexibility on wildcards public void addRectangle(List shapes) { shapes.add(0, new Rectangle()); // compile-time error! }

Generic Methods This is a method takes an array of objects and a collection and puts all objects in the array into the collection. static void fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); // compile time error }

Generic Methods This can be solved using the generic methods static void fromArrayToCollection(T[] a, Collection c) { for (T o : a) { c.add(o); // correct } This method can be called with any kind of collection whose element type is a supertype of the element of the array Object[] oa = new Object[100]; Collection co = new ArrayList (); fromArrayToCollection(oa, co);// T inferred to be Object String[] sa = new String[100]; Collection cs = new ArrayList (); fromArrayToCollection(sa, cs);// T inferred to be String

Using Legacy Code in Generic Code Use of generics with legacy code Consider the package package com.Foolibar.widgets package com.Fooblibar.widgets; public interface Part {...} public class Inventory { /** * Adds a new Assembly to the inventory database. * The assembly is given the name name, and consists of a set * parts specified by parts. All elements of the collection parts * must support the Part interface. **/ public static void addAssembly(String name, Collection parts) {...} public static Assembly getAssembly(String name) {...} public interface Assembly { Collection getParts(); // Returns a collection of Parts }

Contd.. package com.mycompany.inventory; import com.Fooblibar.widgets.*; public class Blade implements Part {... } public class Guillotine implements Part { } public class Main { public static void main(String[] args) { Collection c = new ArrayList (); c.add(new Guillotine()) ; c.add(new Blade()); Inventory.addAssembly("thingee", c); Collection k = Inventory.getAssembly("thingee").getParts(); } addAssembly, it expects the second parameter to be of type Collection. The actual argument is of type Collection.

Contd.. ➲ A generic type like Collection is used without a type parameter, it's called a raw type. ➲ Most people's first instinct is that Collection really means Collection. ➲ Sometimes It's more accurate to say that the type Collection denotes a collection of some unknown type, just like Collection. ➲ Raw types are very much like wildcard types, but they are not typechecked as stringently. This is a deliberate design decision, to allow generics to interoperate with pre-existing legacy code. ➲ Pay close attention to the unchecked warnings when you intermix legacy and generic code

Using Generic code in Legacy Code Generic Code package com.Fooblibar.widgets; public interface Part {... } public class Inventory { /** * Adds a new Assembly to the inventory database. * The assembly is given the name name, and consists of a set * parts specified by parts. All elements of the collection parts * must support the Part interface. **/ public static void addAssembly(String name, Collection parts) {...} public static Assembly getAssembly(String name) {...} } public interface Assembly { Collection getParts(); // Returns a collection of Parts }

Generic to Legacy Legacy code package com.mycompany.inventory; import com.Fooblibar.widgets.*; public class Blade implements Part {... } public class Guillotine implements Part { } public class Main { public static void main(String[] args) { Collection c = new ArrayList(); c.add(new Guillotine()) ; c.add(new Blade()); Inventory.addAssembly("thingee", c); // 1: unchecked warning} Collection k = Inventory.getAssembly("thingee").getParts(); } Line 1 generates an unchecked warning, because a raw Collection is being passed in where a Collection of Parts is expected, and the compiler cannot ensure that the raw Collection really is a Collection of Parts

The Fine Print What does the following code fragment print? List l1 = new ArrayList (); List l2 = new ArrayList (); System.out.println(l1.getClass() == l2.getClass()); Instances of a generic class have the same run-time class, regardless of their actual type parameters

Casts and InstanceOf It usually makes no sense to ask an instance if it is an instance of a particular invocation of a generic type: Collection cs = new ArrayList (); if (cs instanceof Collection ) {...} // Illegal. Similarly, a cast such as Collection cstr = (Collection ) cs; // Unchecked warning, gives an unchecked warning, The same is true of type variables T badCast(T t, Object o) {return (T) o; // Unchecked warning. }

Class Literals as Runtime-Type Tokens ● One of the changes in JDK 1.5 is that the class java.lang.Class is generic. ● Now the class has a parameter T which stands for the type that the class object is representing. ● For example, the type of String.class is Class and the type of Serializable.class is Class.This is used to improve the type safety of reflection code.

Contd.. For example, suppose you need to write a utility method that performs a database query, given as a string of SQL, and returns a collection of objects in the database that match that query. One way is to pass in a factory object explicitly, writing code like: interface Factory { T make();} public Collection select(Factory factory, String statement) { Collection result = new ArrayList (); /* Run sql query using jdbc */ for (/* Iterate over jdbc results. */) { T item = factory.make(); /* Use reflection and set all of item's fields from sql results. */ result.add(item); } return result; }

Contd.. You can call this either as select(new Factory (){ public EmpInfo make() { return new EmpInfo(); }}, ”selection string”); or you can declare a class EmpInfoFactory to support the Factory interface class EmpInfoFactory implements Factory {... public EmpInfo make() { return new EmpInfo();} } and call it select(getMyEmpInfoFactory(), ”selection string”);

Acknowledgements ● /generics.html /generics.html ● 07/index.html

Thank You