Goal Give an overview of generics for the Java programming language - - PDF document

goal
SMART_READER_LITE
LIVE PREVIEW

Goal Give an overview of generics for the Java programming language - - PDF document

Generics Written in the Java Programming Language with Parameterized Types in Java Platform 5.0 Angelika Langer Trainer/Consultant www.AngelikaLanger.com TS-5627 2005 JavaOne SM Conference | Session TS-5627 1 Goal Give an overview


slide-1
SLIDE 1

1 2005 JavaOneSM Conference | Session TS-5627

Generics Written in the Java™ Programming Language with Parameterized Types in Java Platform 5.0

Angelika Langer Trainer/Consultant www.AngelikaLanger.com

TS-5627

2005 JavaOneSM Conference | Session TS-5627 | 2

Give an overview of generics for the Java™ programming language What are generics?

Language features of generics

What are generics used for?

Idioms for use of generics

Goal

slide-2
SLIDE 2

2005 JavaOneSM Conference | Session TS-5627 | 3

Speaker’s Qualifications

  • Author of Java Generics FAQ online
  • www.AngelikaLanger.com/GenericsFAQ/

JavaGenericsFAQ.html

  • Independent trainer/consultant/author
  • Teaching C++ and Java for 10+ years

2005 JavaOneSM Conference | Session TS-5627 | 4

Agenda

Language Features Usage

slide-3
SLIDE 3

2005 JavaOneSM Conference | Session TS-5627 | 5

Non-Generic Collections

  • No homogeneous collections
  • Lots of casts required
  • No compile-time checks
  • Late error detection at runtime

Li nkedLi st l i st = new Li nkedLi st ( ) ; l i st . add( new I nt eger ( 0) ) ; I nt eger i = ( I nt eger ) l i st . get ( 0) ; St r i ng s = ( St r i ng) l i st . get ( 0) ;

Casts Required Fine at Compile-time, but Fails at Runtime

2005 JavaOneSM Conference | Session TS-5627 | 6

Generic Collections

  • Collections are homogeneous
  • No casts necessary
  • Early compile-time checks
  • Based on static type information

Li nkedLi st <I nt eger > l i st = new Li nkedLi st <I nt eger > ( ) ; l i st . add( new I nt eger ( 0) ) ; I nt eger i = l i st . get ( 0) ; St r i ng s = l i st . get ( 0) ;

Compile-time Error

slide-4
SLIDE 4

2005 JavaOneSM Conference | Session TS-5627 | 7

Benefits of Generic Types

  • Increased expressive power
  • Improved type safety
  • Explicit type parameters and implicit type casts

2005 JavaOneSM Conference | Session TS-5627 | 8

Definition of Generic Types

  • Type variable = “placeholder” for an unknown type
  • Similar to a type, but not really a type
  • Several restrictions
  • Not allowed in newexpressions, cannot be derived from,

no class literal

i nt er f ace Col l ect i on<A> { publ i c voi d add ( A x) ; publ i c I t er at or <A> i t er at or ( ) ; } cl ass Li nkedLi st <A> i m pl em ent s Col l ect i on<A> { pr ot ect ed cl ass Node { A el t ; Node next = nul l ; Node ( A el t ) { t hi s. el t = el t ; } } . . . }

slide-5
SLIDE 5

2005 JavaOneSM Conference | Session TS-5627 | 9

Type Parameter Bounds

publ i c cl ass Tr eeM ap<K ext ends Com par abl e <K>, V> { pr i vat e st at i c cl ass Ent r y<K, V> { . . . } … pr i vat e Ent r y<K, V> get Ent r y( K key) { … whi l e ( p ! = nul l ) { i nt cm p = k. com par eTo ( p. key) ; … } … } … } publ i c i nt er f ace Com par abl e<T> { publ i c i nt com par eTo( T ar g) ; }

  • Bounds = supertype of a type variable
  • Purpose: make available non-static methods of a type variable
  • Limitations: gives no access to constructors or static methods

2005 JavaOneSM Conference | Session TS-5627 | 10

Using Generic Types

  • Can use generic types with or without

type argument specification

  • With concrete type arguments
  • Concrete instantiation
  • Without type arguments
  • Raw type
  • With wildcard arguments
  • Wildcard instantiation
slide-6
SLIDE 6

2005 JavaOneSM Conference | Session TS-5627 | 11

Concrete Instantiation

  • Type argument is a concrete type
  • More expressive type information
  • Enables compile-time type checks

voi d pr i nt Di r ect or yNam es( Col l ect i on<Fi l e> f i l es) { f or ( Fi l e f : f i l es) i f ( f . i sDi r ect or y( ) ) Syst em . out . pr i nt l n( f ) ; } Li st <Fi l e> t ar get Di r = new Li nkedLi st <Fi l e>( ) ; ... fill list with Fi l e objects ... pr i nt Di r ect or yNam es( t ar get Di r ) ;

2005 JavaOneSM Conference | Session TS-5627 | 12

Raw Type

  • No type argument specified
  • Permitted for compatibility reasons
  • Permits mix of non-generic (legacy) code with generic code

voi d pr i nt Di r ect or yNam es( Col l ect i on f i l es) { f or ( I t er at or i t = f i l es. i t er at or ( ) ; i t . hasNext ( ) ; ) { Fi l e f = ( Fi l e) i t . next ( ) ; i f ( f . i sDi r ect or y( ) ) Syst em . out . pr i nt l n( f ) ; } } Li st <Fi l e> t ar get Di r = new Li nkedLi st <Fi l e>( ) ; ... fill list with Fi l e objects ... pr i nt Di r ect or yNam es( t ar get Di r ) ;

slide-7
SLIDE 7

2005 JavaOneSM Conference | Session TS-5627 | 13

Wildcard Instantiation

  • Type argument is a wildcard
  • A wildcard stands for a family of types
  • Bounded and unbounded wildcards supported

voi d pr i nt El em ent s( Col l ect i on<?> c) { f or ( O bj ect e : c) Syst em . out . pr i nt l n( e) ; } Col l ect i on <Fi l e> t ar get Di r = new Li nkedLi st <Fi l e>( ) ; ... fill list with Fi l e objects ... pr i nt El em ent s( t ar get Di r ) ;

2005 JavaOneSM Conference | Session TS-5627 | 14

Wildcards

  • A wildcard denotes a representative

from a family of types

  • Unbounded wildcard

?

  • All types
  • Lower-bound wildcard

? extends supertype

  • All types that are subtypes of supertype
  • Upper-bound wildcard

? super subtype

  • All types that are supertypes of subtype
slide-8
SLIDE 8

2005 JavaOneSM Conference | Session TS-5627 | 15

Example of a Bounded Wildcard

  • Consider a method
  • That draws objects from a class hierarchy of shapes
  • Method cannot draw a list of circles
  • Because list<circle> is not a subtype of list<shape>

voi d dr awAl l ( Li st <Shape> shapes) { f or ( Shape s : shapes)

  • s. dr aw

( ) ; }

Naïve approach

Li st <Ci r cl e> ci r cl es = . . . ; dr awAl l ( ci r cl es) ;

Incompatible Argument Type

2005 JavaOneSM Conference | Session TS-5627 | 16

Trying to Fix It…

  • Try a wildcard instantiation
  • Compiler needs more information

about “unknown” type

voi d dr awAl l ( Li st <?> shapes) { f or ( Shape s : shapes)

  • s. dr aw

( ) ; }

Wildcarded version

Error: ? Does Not Have a Draw Method

slide-9
SLIDE 9

2005 JavaOneSM Conference | Session TS-5627 | 17

Solution: Upper Bound Wildcard

  • "? Ext ends shape" stands for “any subtype of shape”
  • Shape is the upper bound of the bounded wildcard
  • Col l ect i on<? Ext ends shape> stands for

“collection of any kind of shapes”

  • Is the supertype of all collections that contain shapes

(or subtypes thereof)

Li st <Ci r cl e> ci r cl es = . . . ; dr awAl l ( ci r cl es) ;

fine

voi d dr awAl l ( Li st <? ext ends Shape > shapes) { f or ( Shape s : shapes)

  • s. dr aw

( ) ; }

2005 JavaOneSM Conference | Session TS-5627 | 18

Generic Methods

  • Defining a generic method

cl ass Ut i l i t i es { publ i c st at i c <A ext ends Com par abl e <A>> A m ax( I t er abl e<A> c) { A r esul t = nul l ; f or ( A a : c) { i f ( r esul t == nul l | | r esul t . com par eTo( a) < 0) r esul t = a; } } }

slide-10
SLIDE 10

2005 JavaOneSM Conference | Session TS-5627 | 19

Type Inference

  • Invoking a generic method
  • No special invocation syntax
  • Type arguments are inferred from actual arguments

(! type inference)

publ i c st at i c voi d m ai n ( St r i ng[ ] ar gs) { Li nkedLi st <Byt e> byt eLi st = new Li nkedLi st <Byt e>( ) ; . . . Byt e y = Ut i l i t i es. m ax ( byt eLi st ) ; }

2005 JavaOneSM Conference | Session TS-5627 | 20

Compilation Model

  • Code specialization
  • New representation for every instantiation of a

generic type or method

  • e.g., Different code for a list of strings and list of integers
  • Downside: code bloat
  • Code sharing
  • Only one representation of a generic type or method
  • All concrete instantiations are mapped to this representation
  • Implicit type checks and type conversions where needed
  • Downside: no primitive types
slide-11
SLIDE 11

2005 JavaOneSM Conference | Session TS-5627 | 21

Type Erasure—Class Definition

  • Generic type

cl ass Li nkedLi st <A> i m pl em ent s Col l ect i on<A> { pr ot ect ed cl ass Node { A el t ; Node next = nul l ; Node ( A el t ) { t hi s. el t = el t ; } } publ i c voi d add ( A el t ) { . . . } . . . } cl ass Li nkedLi st i m pl em ent s Col l ect i on { pr ot ect ed cl ass Node { Obj ect el t ; Node next = nul l ; Node ( Obj ect el t ) { t hi s. el t = el t ; } } publ i c voi d add ( Obj ect el t ) { . . . } . . . }

  • After type erasure

2005 JavaOneSM Conference | Session TS-5627 | 22

Type Erasure—Usage Context

f i nal cl ass Test { publ i c st at i c voi d m ai n ( St r i ng[ ] ar gs) { Li nkedLi st <St r i ng> ys = new Li nkedLi st <St r i ng> ( ) ;

  • ys. add( " zer o" ) ; ys. add( " one" ) ;

St r i ng y = ys. i t er at or ( ) . next ( ) ; } } f i nal cl ass Test { publ i c st at i c voi d m ai n ( St r i ng[ ] ar gs) { Li nkedLi st ys = new Li nkedLi st ( ) ;

  • ys. add( " zer o" ) ; ys. add( " one" ) ;

St r i ng y = ( St r i ng)ys. i t er at or ( ) . next ( ) ; } }

Additional Cast

  • Generic type
  • After type erasure
slide-12
SLIDE 12

2005 JavaOneSM Conference | Session TS-5627 | 23

Agenda

Language Features Usage

2005 JavaOneSM Conference | Session TS-5627 | 24

Categories of Usage

  • Using predefined generic types/methods
  • e.g., using collections such as Li st <Dat e>
  • Requires relatively little learning effort
  • Provide concrete type arguments to generic types
  • Rely on type inference when calling generic methods
  • Designing and defining generic types/methods
  • e.g., implementing a generic Li nkedLi st <T> class
  • Requires sound understanding of generics
slide-13
SLIDE 13

2005 JavaOneSM Conference | Session TS-5627 | 25

Using a Predefined Generic Type

  • Demonstrates a key benefit of generics
  • Source code is more readable and precise

than without generics

publ i c st at i c Col l ect i on<St r i ng> r em

  • veDi r ect or y( Col l ect i on<Fi l e> absol ut eFi l es,

St r i ng di r ect or yToBeRem

  • vedFr om

Pat h) { Col l ect i on<St r i ng> r el at i veFi l eNam es = new HashSet <St r i ng> ( ) ; I t er at or <Fi l e> i t er = absol ut eFi l es. i t er at or ( ) ; whi l e ( i t er . hasNext ( ) ) { r el at i veFi l eNam

  • es. add(

Fi l eUt i l i t y. r el at i vePat h( i t er . next ( ) . get Pat h( ) , di r ect or yToBeRem

  • vedFr om

Pat h) ) ; } r et ur n r el at i veFi l eNam es; }

2005 JavaOneSM Conference | Session TS-5627 | 26

Same Code Without Generics

  • It’s difficult to tell what the collections contain

publ i c st at i c Col l ect i on r em

  • veDi r ect or y( Col l ect i on absol ut eFi l es,

St r i ng di r ect or yToBeRem

  • vedFr om

Pat h) { Col l ect i on r el at i veFi l eNam es = new HashSet ( ) ; I t er at or i t er = absol ut eFi l es. i t er at or ( ) ; whi l e ( i t er . hasNext ( ) ) { r el at i veFi l eNam

  • es. add(

Fi l eUt i l i t y. r el at i vePat h( ( ( Fi l e) i t er . next ( ) ) . get Pat h( ) , di r ect or yToBeRem

  • vedFr om

Pat h) ) ; } r et ur n r el at i veFi l eNam es; }

slide-14
SLIDE 14

2005 JavaOneSM Conference | Session TS-5627 | 27

Designing and Defining a Generic Type

  • Case study
  • Implement a class that

holds two elements

  • f different types
  • Constructors
  • Getters and setter
  • Equality and hashing
  • Comparability
  • Cloning
  • Value semantics

f i nal cl ass Pai r <X, Y> { pr i vat e X f i r st ; pr i vat e Y second; . . . }

2005 JavaOneSM Conference | Session TS-5627 | 28

Getters and Setters

  • Add setters that take the new value

from another pair

f i nal cl ass Pai r <X, Y> { . . . publ i c X get Fi r st ( ) { r et ur n f i r st ; } publ i c Y get Second( ) { r et ur n second; } publ i c voi d set Fi r st ( X x) { f i r st = x; } publ i c voi d set Second( Y y) { second = y; } }

slide-15
SLIDE 15

2005 JavaOneSM Conference | Session TS-5627 | 29

Constructors—First Naïve Approach

f i nal cl ass Pai r <X, Y> { . . . publ i c Pai r ( X x, Y y) { f i r st = x; second = y; } publ i c Pai r ( ) { f i r st = nul l ; second = nul l ; } publ i c Pai r ( Pai r ot her ) { i f ( ot her == nul l ) { f i r st = nul l ; second = nul l ; } el se { f i r st = ot her . f i r st ; second = ot her . second; } } }

er r or : i ncom pat i bl e t ypes

Obj ect Y

  • Does not compile

2005 JavaOneSM Conference | Session TS-5627 | 30

Constructors—Tentative Fix

f i nal cl ass Pai r <X, Y> { . . . publ i c Pai r ( X x, Y y) { f i r st = x; second = y; } publ i c Pai r ( ) { f i r st = nul l ; second = nul l ; } publ i c Pai r ( Pai r ot her ) { i f ( ot her == nul l ) { f i r st = nul l ; second = nul l ; } el se { f i r st = ( X) ot her . f i r st ; second = ( Y) ot her . second; } } }

war ni ng: unchecked cast

Y Y

  • Insert cast
slide-16
SLIDE 16

2005 JavaOneSM Conference | Session TS-5627 | 31

Ignoring Unchecked Warnings

  • What happens if we ignore the warnings?
  • Error detection at runtime
  • Long after debatable assigment in constructor

Pai r <St r i ng, I nt eger> p1 = new Pai r <St r i ng, I nt eger >( " Bobby" , 10) ; Pai r <St r i ng, Dat e > p2 = new Pai r <St r i ng, Dat e>( p1) ; . . . Dat e bobbysBi r t hday = p2. get Second( ) ; Cl assCast Except i on

2005 JavaOneSM Conference | Session TS-5627 | 32

Constructors—What’s the Goal?

  • A constructor that takes the same type of pair?
  • Allow creation of one pair from another pair of

a different type, but with compatible members?

slide-17
SLIDE 17

2005 JavaOneSM Conference | Session TS-5627 | 33

Same Type Argument

f i nal cl ass Pai r <X, Y> { … publ i c Pai r ( Pai r <X, Y> ot her ) { i f ( ot her == nul l ) { f i r st = nul l ; second = nul l ; } el se { f i r st = ot her . f i r st ; second = ot her . second; } } } Pai r <St r i ng, I nt eger> p1 = new Pai r <St r i ng, I nt eger >( " Bobby" , 10) ; Pai r <St r i ng, Dat e > p2 = new Pai r <St r i ng, Dat e>( p1) ; . . . Dat e bobbysBi r t hday = p2. get Second( ) ;

er r or : no m at chi ng ct or

  • Accepts same

type pair

  • Rejects alien pair

2005 JavaOneSM Conference | Session TS-5627 | 34

Downside

  • Implementation also rejects useful cases

Pai r <St r i ng, I nt eger> p1 = new Pai r <St r i ng, I nt eger >( " pl anet ear t h" , 10000) ; Pai r <St r i ng, Num ber> p2 = new Pai r <St r i ng, Num ber >( p1) ; l ong t hePl anet sAge = p2. get Second( ) . l ongVal ue( ) ;

er r or : no m at chi ng ct or

slide-18
SLIDE 18

2005 JavaOneSM Conference | Session TS-5627 | 35

Compatible Type Argument

f i nal cl ass Pai r <X, Y> { … publ i c <A ext ends X, B ext ends Y > Pai r ( Pai r <A, B> ot her ) { i f ( ot her == nul l ) { f i r st = nul l ; second = nul l ; } el se { f i r st = ot her . f i r st ; second = ot her . second; } } } Pai r <St r i ng, I nt eger> p1 = new Pai r <St r i ng, I nt eger >( " pl anet ear t h" , 10000) ; Pai r <St r i ng, Num ber> p2 = new Pai r <St r i ng, Num ber >( p1) ; l ong t hePl anet sAge = p2. get Second( ) . l ongVal ue( ) ; now f i ne

  • Accepts

compatible pair

2005 JavaOneSM Conference | Session TS-5627 | 36

Equivalent Implementation

  • Permits the same invocations

f i nal cl ass Pai r <X, Y> { … publ i c Pai r ( Pai r <? ext ends X, ? ext ends Y> ot her ) { i f ( ot her == nul l ) { f i r st = nul l ; second = nul l ; } el se { f i r st = ot her . f i r st ; second = ot her . second; } } } Pai r <St r i ng, I nt eger> p1 = new Pai r <St r i ng, I nt eger >( " pl anet ear t h" , 10000) ; Pai r <St r i ng, Num ber> p2 = new Pai r <St r i ng, Num ber >( p1) ; l ong t hePl anet sAge = p2. get Second( ) . l ongVal ue( ) ; f i ne

slide-19
SLIDE 19

2005 JavaOneSM Conference | Session TS-5627 | 37

Equivalent Implementation

  • Permit same invocations
  • Difference lies in access to wildcard argument
  • Not all methods of wildcard pair can be called
  • Doesn’t matter here, since we do not invoke any

methods

f i nal cl ass Pai r <X, Y> { … publ i c Pai r ( Pai r <? ext ends X, ? ext ends Y> ot her ) { … } } f i nal cl ass Pai r <X, Y> { … publ i c <A ext ends X, B ext ends Y > Pai r ( Pai r <A, B> ot her ) { … } }

2005 JavaOneSM Conference | Session TS-5627 | 38

Wildcard Access Rules

  • Disallowed
  • Invoking methods that take arguments of

“unknown” type

  • We do not know which type of elements a l i st <?> Contains
  • Hence we cannot add anything, except the typeless null
  • Allowed:
  • Invoking methods that return objects of “unknown” type
  • After all it’s an obj ect

Pai r <?, ?> p = new Pai r <Dat e, Dat e>( ) ;

  • p. set Fi r st ( " xm

as" ) ;

  • p. set Fi r st ( nul l ) ;

O bj ect

  • = p. get Fi r st ( ) ;

Error

slide-20
SLIDE 20

2005 JavaOneSM Conference | Session TS-5627 | 39

Value Semantics

  • Alternative semantics
  • Hold copies of constructor arguments,

instead of just references

f i nal cl ass Val uePai r <X, Y> { publ i c Val uePai r ( X x, Y y) { f i r st = ( x==nul l ) ?nul l : cl oneObj ect( x) ; second = ( y==nul l ) ?nul l : cl oneObj ect( y) ) ; }

pr i vat e st at i c <T> T cl oneO bj ect ( T t ) { t r y { r et ur n ( T) t . get Cl ass( ) . get M et hod( " cl one" , nul l ) . i nvoke( t , nul l ) ; } cat ch ( Except i on e) { r et ur n nul l ; } }

}

2005 JavaOneSM Conference | Session TS-5627 | 40

Cloning

  • Unchecked cast cannot be avoided
  • Use @

Suppr essW ar ni ngs annotation

f i nal cl ass Val uePai r <X, Y> { pr i vat e st at i c <T> T cl oneObj ect ( T t ) { … r et ur n ( T) t . get Cl ass( ) . get M et hod( " cl one" , nul l ) . i nvoke( t , nul l ) ; … } } war ni ng: unchecked cast f i nal cl ass Val uePai r <X, Y> { @ Suppr essW ar ni ngs( " unchecked" ) pr i vat e st at i c <T> T cl oneObj ect ( T t ) { … r et ur n ( T) t . get Cl ass( ) . get M et hod( " cl one" , nul l ) . i nvoke( t , nul l ) ; … } }

slide-21
SLIDE 21

2005 JavaOneSM Conference | Session TS-5627 | 41

Default Constructed Value Pair

  • Default construction of a value pair is a problem
  • Generic construction not permitted
  • Generic construction only possible via reflection
  • Typically by a factory method

f i nal cl ass Val uePai r <X , Y> { … publ i c Val uePai r ( ) { f i r st = new X( ); second = new Y( ); } … }

er r or : t ype var i abl e not per m i t t ed i n new expr essi on

2005 JavaOneSM Conference | Session TS-5627 | 42

Generic Object Creation

  • Static helper method that produces an object
  • If information about requested type of object

is provided

f i nal cl ass Val uePai r <X, Y> { publ i c Val uePai r ( ) { f i r st = m akeObj ect( X. cl ass) ; second = m akeObj ect( Y. cl ass) ; } pr i vat e st at i c <T> T m akeObj ect ( Cl ass<T> cl azz){ t r y { r et ur n cl azz. get Const r uct or ( new Cl ass[ 0] ) . newI nst ance( new O bj ect [ 0] ) ; } cat ch ( Except i on e) { r et ur n nul l ; } } }

slide-22
SLIDE 22

2005 JavaOneSM Conference | Session TS-5627 | 43

Class Cl ass<T>

  • Class Cl ass is generic
  • Type parameter is the type that the Cl ass object represents
  • e.g., St r i ng. cl ass is of type Cl ass<St r i ng>
  • Used here to ensure consistency
  • To create a T object a Cl ass<T> object must be provided
  • Nonsense will not compile

pr i vat e st at i c <T> T m akeO bj ect ( Cl ass<T> cl azz) { … } Dat e dat e = m akeO bj ect ( St r i ng. cl ass ) ;

er r or

2005 JavaOneSM Conference | Session TS-5627 | 44

No Class Literals for Type Variables

  • Default construction is still a problem
  • We cannot call the helper method
  • Type variables have no class literal

f i nal cl ass Val uePai r <X, Y> { publ i c Val uePai r ( ) { f i r st = m akeObj ect( X. cl ass) ; second = m akeObj ect( Y. cl ass) ; }

pr i vat e st at i c <T> T m akeO bj ect ( Cl ass<T> cl azz) { … }

}

er r or : cl ass l i t er al does not exi st

slide-23
SLIDE 23

2005 JavaOneSM Conference | Session TS-5627 | 45

Provide Class Objects

  • Special purpose constructor
  • Takes the required class objects as arguments
  • The constructor would be used like this
  • Note the highly redundant repetition of type information

f i nal cl ass Val uePai r <X, Y> { publ i c Val uePai r ( Cl ass<X> xType, Cl ass<Y> yType) { f i r st = m akeO bj ect ( xType) ; second = m akeO bj ect ( yType) ; }

pr i vat e st at i c <T> T m akeO bj ect ( Cl ass<T> cl azz) { … }

} Val uePai r <St r i ng, Dat e> pai r = new Val uePai r <St r i ng, Dat e>( St r i ng. cl ass , Dat e. cl ass) ;

2005 JavaOneSM Conference | Session TS-5627 | 46

Factory Method for Value Pair

  • Factory method = static method that produces an object
  • Use instead of a constructor
  • Factory method is more convenient to use
  • Type information is automatically inferred

f i nal cl ass Val uePai r <X, Y> { publ i c st at i c <U, V> Val uePai r <U, V> m akeDef aul t Pai r( Cl ass<U> uType, Cl ass<V> vType) { r et ur n new Val uePai r <U, V>( m akeO bj ect ( uType) , m akeO bj ect ( vType) ) ; } pr i vat e st at i c <T> T m akeO bj ect ( Cl ass<T> cl azz) { … } } Val uePai r <St r i ng, Dat e> pai r = Val uePai r . m akeDef aul t Pai r ( St r i ng. cl ass , Dat e. cl ass ) ;

slide-24
SLIDE 24

2005 JavaOneSM Conference | Session TS-5627 | 47

Comparison

  • Use bounds to require that members be comparable

f i nal cl ass Pai r <X, Y> i m pl em ent s Com par abl e<Pai r <X, Y>> { … publ i c i nt com par eTo( Pai r <X, Y> ot her ) { . . . f i r st . com par eTo( ot her . f i r st ) . . . . . . second. com par eTo( ot her . second) . . . } } er r or : cannot f i nd com par eTo m et hod f i nal cl ass Pai r <X ext ends Com par abl e<X> , Y ext ends Com par abl e<Y> > i m pl em ent s Com par abl e<Pai r <X, Y>> { … publ i c i nt com par eTo( Pai r <X, Y> ot her ) { . . . f i r st . com par eTo( ot her . f i r st ) . . . . . . second. com par eTo( ot her . second) . . . } } now f i ne

2005 JavaOneSM Conference | Session TS-5627 | 48

Comparison

  • The proposed implementation does not

permit pairs of “incomparable” types

  • Such as Pai r <Num

ber , Num ber >

  • Two flavours of parameterized pair class

would be ideal

f i nal cl ass Pai r <X, Y> { . . . }

er r or : i dent i cal t ype er asur e

f i nal cl ass Pai r <X ext ends Com par abl e<X>, Y ext ends Com par abl e<Y> > i m pl em ent s Com par abl e<Pai r <X, Y>> { . . . }

slide-25
SLIDE 25

2005 JavaOneSM Conference | Session TS-5627 | 49

Multi-Class Solution

  • Defining separate classes
  • Leads to an inflation of classes

f i nal cl ass Com par abl ePai r<X ext ends Com par abl e<X>, Y ext ends Com par abl e<Y>> i m pl em ent s Com par abl e<Com par abl ePai r <X, Y>> { publ i c i nt com par eTo( Com par abl ePai r <X, Y> ot her ) { . . . f i r st . com par eTo( ot her . f i r st ) . . . . . . second. com par eTo( ot her . second) . . . } } f i nal cl ass Pai r <X, Y> { . . . }

2005 JavaOneSM Conference | Session TS-5627 | 50

Single-Class Solution

  • Requires cast
  • Use @

Suppr essW ar ni ngs annotation

f i nal cl ass Pai r <X, Y> i m pl em ent s Com par abl e<Pai r <X, Y>> { publ i c i nt com par eTo( Pai r <X, Y> ot her ) { . . . ( ( Com par abl e<X>)f i r st ) . com par eTo( ot her . f i r st ) . . . . . . ( ( Com par abl e<Y>)second) . com par eTo( ot her . second) . . . } } war ni ng: unchecked cast f i nal cl ass Pai r <X, Y> i m pl em ent s Com par abl e<Pai r <X, Y>> { @ Suppr essW ar ni ngs( " unchecked" ) publ i c i nt com par eTo( Pai r <X, Y> ot her ) { . . . ( ( Com par abl e<X>) f i r st ) . com par eTo( ot her . f i r st ) . . . . . . ( ( Com par abl e<Y>) second) . com par eTo( ot her . second) . . . } }

slide-26
SLIDE 26

2005 JavaOneSM Conference | Session TS-5627 | 51

Summary

  • Java platform 5.0 has language features for

definition and use of generic types and methods

  • Type parameters and arguments, wildcards, bounds…
  • Using predefined generic types is easy
  • Designing and implementing generic APIs

is challenging

  • Requires understanding of compilation model,

various restrictions, and options…

2005 JavaOneSM Conference | Session TS-5627 | 52

For More Information

  • Generics in the Java Programming Language
  • A tutorial by Gilad Bracha, July 2004
  • http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
  • Java Language Specification, 3rd Edition
  • By Gosling, Joy, Steele, Bracha, May 2005
  • http://java.sun.com/docs/books/jls
  • Java Generics FAQ
  • A FAQ by Angelika Langer
  • http://www.AngelikaLanger.com/GenericsFAQ/JavaGenericsFAQ.html
  • More links...
  • http://www.AngelikaLanger.com/Resources/Links/

JavaGenerics.htm

slide-27
SLIDE 27

2005 JavaOneSM Conference | Session TS-5627 | 53

Q&A

Angelika Langer

2005 JavaOneSM Conference | Session TS-5627 | 54

Submit Session Evaluations for Prizes!

  • You can win a $75.00 gift certificate to the on-site

Retail Store by telling Sun what you think!

  • Turn in completed forms to enter the daily drawing
  • Each evaluation must be turned in the same day as

the session presentation

  • Five winners will be chosen each day

(Sun will send the winners e-mail)

  • Drop-off locations: give to the room monitors or use any
  • f the three drop-off stations in the North and South Halls

Note: Winners on Thursday, 6/30, will receive and can redeem certificates via e-mail.

Your opinions are important to Sun

slide-28
SLIDE 28

55 2005 JavaOneSM Conference | Session TS-5627

Generics Written in the Java™ Programming Language with Parameterized Types in Java Platform 5.0

Angelika Langer Trainer/Consultant www.AngelikaLanger.com

TS-5627