Generics In Java 1.5 - PowerPoint PPT Presentation

About This Presentation
Title:

Generics In Java 1.5

Description:

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. – PowerPoint PPT presentation

Number of Views:83
Avg rating:3.0/5.0
Slides: 28
Provided by: csRitEdu2
Learn more at: https://www.cs.rit.edu
Category:
Tags: generics | java

less

Transcript and Presenter's Notes

Title: Generics In Java 1.5


1
Generics In Java 1.5
  • By
  • Manjunath Beeraladinni

2
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.

3
Comparison
  • In JDK1.4
  • List myIntList new LinkedList()
  • myIntList.add(new Integer(0))
  • Integer x (Integer) myIntList.iterator().next()
  • In JDK1.5
  • ListltIntegergt myIntList new LinkedListltIntegergt(
    )
  • myIntList.add(new Integer(0))
  • Integer x myIntList.iterator().next()

4
Defining Simple Generics
  • The definition of list and Iterator in java.util
  • public interface ListltEgt void add(E x)
  • IteratorltEgt iterator()
  • public interface IteratorltEgt E next()
  • boolean hasNext()

5
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.

6
Generics and Sub typing
  • Consider the code snippet
  • ListltStringgt list_str new ArrayListltStringgt()
    //1
  • ListltObjectgt 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.

7
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 lt c.size() k)
  • System.out.println(i.next())

8
WildCards
  • Same routine using JDK1.5
  • void printCollection(CollectionltObjectgt c)
  • for (Object e c)
  • System.out.println(e)

9
WildCards
  • WildCard invocation
  • void printCollection(Collectionlt?gt c)
  • for (Object e c)
  • System.out.println(e)

10
WildCards
  • Unsafe to Add objects using add()
  • Collectionlt?gt c new ArrayListltStringgt()
  • c.add(new Object()) // compile time error
  • We can use get() method.

11
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
  • .....

12
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(ListltShapegt shapes)
  • for (Shape s shapes)
  • s.draw(this)
  • This DrawAll() can only be used on a list of type
    SHAPE.

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

14
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,
    Collectionlt?gt c)
  • for (Object o a)
  • c.add(o) // compile time error

15
Generic Methods
  • This can be solved using the generic methods
  • static ltTgt void fromArrayToCollection(T a,
    CollectionltTgt 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 Object100
  • CollectionltObjectgt co new ArrayListltObjectgt()
  • fromArrayToCollection(oa, co)// T inferred to be
    Object
  • String sa new String100
  • CollectionltStringgt cs new ArrayListltStringgt()
  • fromArrayToCollection(sa, cs)// T inferred to be
    String

16
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

17
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)
  • CollectionltPartgt c new
    ArrayListltPartgt()
  • c.add(new Guillotine())
  • c.add(new Blade())
  • Inventory.addAssembly("thingee", c)
  • CollectionltPartgt k Inventory.getAssembly
    ("thingee").getParts()

18
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 CollectionltObjectgt.
  • Sometimes It's more accurate to say that the type
    Collection denotes a collection of some unknown
    type, just like Collectionlt?gt.
  • 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

19
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,
    CollectionltPartgt parts) ...
  • public static Assembly getAssembly(String
    name) ...

20
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("thin
    gee").getParts()

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

22
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 ArrayListltStringgt()
  • if (cs instanceof CollectionltStringgt) ... //
    Illegal.
  • Similarly, a cast such as
  • CollectionltStringgt cstr (CollectionltStringgt)
    cs // Unchecked warning,
  • gives an unchecked warning,
  • The same is true of type variables
  • ltTgt T badCast(T t, Object o) return (T) o //
    Unchecked warning.

23
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
    ClassltStringgt and the type of Serializable.class
    is ClassltSerializablegt.This is used to improve
    the type safety of reflection code.

24
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 FactoryltTgt T make()
  • public ltTgt CollectionltTgt select(FactoryltTgt
    factory, String statement)
  • CollectionltTgt result new ArrayListltTgt()
  • / 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

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

26
Acknowledgements
  • http//java.sun.com/j2se/1.5.0/docs/guide/language
    /generics.html
  • http//www.cs.rit.edu/hpb/Lectures/20051/Java_707
    /index.html

27
  • Thank You
Write a Comment
User Comments (0)
About PowerShow.com