Java Generics Introduction - Syntax Advantages and Pitfalls

54
1 Java Generics Barney Marispini 08.31.05

description

This is the best introduction presentation for Java Generics I have seen ever.

Transcript of Java Generics Introduction - Syntax Advantages and Pitfalls

Page 1: Java Generics Introduction - Syntax Advantages and Pitfalls

1

Java Generics

Barney Marispini08.31.05

Page 2: Java Generics Introduction - Syntax Advantages and Pitfalls

2

Topics• What Are Generics?• The Collections Framework• Points of Interest• Type Erasure• Type Parameters• Bounded Types• Generic Methods And Constructors• Generic Classes And Interfaces• Legacy Conversion• Generics In Context• Summary• Resources• Discussion

Page 3: Java Generics Introduction - Syntax Advantages and Pitfalls

3

What Are Generics?

Page 4: Java Generics Introduction - Syntax Advantages and Pitfalls

4

Generic History 101

• Generics represent the most significant changeto the Java language since the 1.0 release.

• Over five years in the making, JSR 14 (Generics)was one of the first Java Specification Requests.

• Generics are desirable because they let you writecode that is safer and easier to read than codethat is littered with Object variables and casts.

• Generic programming is now achieved via typeparameters as opposed to inheritance.

Page 5: Java Generics Introduction - Syntax Advantages and Pitfalls

5

Life Before Generics

• Generalized classes, interfaces, and methodswere accomplished by operating throughreferences of type Object.

public Object get(int index);

• Explicit casting was required in order to downcastObject to whatever concrete implementationwas being represented.

String value = (String) list.get(0);

• Runtime exceptions ran rampant because typesafety could not be guaranteed by the compiler.

Page 6: Java Generics Introduction - Syntax Advantages and Pitfalls

6

The Generic New World Order

• Generics means parameterized types.– The type upon which a generic method, class, or

interface operates is specified as a parameter.• Generics make it possible to create a single

class, for example, that automatically works withdifferent types of data (Strings, Integers...).

• Type safety is now ensured by the compiler.– All casts are automatic and implicit.

• Generics expand the ability to write reusablecode and do so in a safe, easy, and invitingmanner.

Page 7: Java Generics Introduction - Syntax Advantages and Pitfalls

7

Raw Type vs. Generics Example

• Raw type versionList list = new ArrayList();list.add("1");

String value = (String) list.get(0);

• Generics versionList<String> list = new ArrayList<String>();list.add("1");String value = list.get(0);

Note: The term “raw” refers to a generic type used withoutactual type arguments. List is the raw type of List<E>.

Page 8: Java Generics Introduction - Syntax Advantages and Pitfalls

8

Example Continued...

• Raw type versionList list = new ArrayList();list.add("1");

// Compiler permitslist.add(new Integer(1));// ClassCastExceptionString value = (String) list.get(1);

• Generics versionList<String> list = new ArrayList<String>();list.add("1");

// Compilation errorlist.add(new Integer(1));String value = list.get(1);

Page 9: Java Generics Introduction - Syntax Advantages and Pitfalls

9

The Collections Framework

Page 10: Java Generics Introduction - Syntax Advantages and Pitfalls

10

The Collections Framework

• The entire collections framework has beenreworked using generics.

• Raw types provide a means of backwardcompatibility (syntactic sugar).– Under the hood, when a raw type is used, the compiler

actually substitutes the upper bound of each variable(typically Object) as the actual type argument for thatvariable. The following are equivalent…

List list = new ArrayList(); // Raw TypeList<Object> list = new ArrayList<Object>();

Page 11: Java Generics Introduction - Syntax Advantages and Pitfalls

11

The New & Improved List Interfacepublic interface List<E> extends Collection<E> {

boolean add(E o);E get(int index);Iterator<E> iterator();

}

• E is a type variable or placeholder. It will bereplaced by the actual reference type passed asan argument to the generic class.

Page 12: Java Generics Introduction - Syntax Advantages and Pitfalls

12

List Interface Continued...public interface List<String> extends Collection<String> {

boolean add(String o);String get(int index);Iterator<String> iterator();

}

• The type argument, String, replaces alloccurrences of E at runtime.

// String is passed as the parameterized type

List<String> list = new ArrayList<String>();

Page 13: Java Generics Introduction - Syntax Advantages and Pitfalls

13

Points of Interest

Page 14: Java Generics Introduction - Syntax Advantages and Pitfalls

14

Generic Points of Interest

• The compiler generates only one class.– All invocations share the same generic type.

• Only object reference types can be passed astype parameters.– Primitive types cannot be passed as type parameters.

• Generic type parameters are just like ordinarymethod parameters. When invoked, the passedtype arguments (String) replace the actual typeparameters (E).

Page 15: Java Generics Introduction - Syntax Advantages and Pitfalls

15

Points of Interest Continued...

• A reference of one specific version of a generictype cannot be assigned to a different version ofthe same same generic type.

// Wrong! (Same generic, different versions)listOfStrings = listOfIntegers;// Wrong! (This one’s tricky. Even though String

// subclasses Object, we can’t be sure listOfObjects// is only holding Strings)

listOfObjects = listOfStrings;

• Generics are only implemented in the compiler.– No generic type information is available at runtime due

to erasure.

Page 16: Java Generics Introduction - Syntax Advantages and Pitfalls

16

Type Erasure

Page 17: Java Generics Introduction - Syntax Advantages and Pitfalls

17

The Concept of Erasure

• To ensure backward compatibility, a processcalled type erasure is used to map the newsyntax to the current JVM specification.

• Type erasure is the process of translating orrewriting code that uses generics into non-generic code.

• When generics are compiled, all generic-specificinformation is completely erased.

Page 18: Java Generics Introduction - Syntax Advantages and Pitfalls

18

Erasure Continued...

• During erasure, all type variables are replaced bytheir upper bound or Object if not specified.

// The erasure of T is Number<T extends Number>

// The erasure of T is Object<T>

• The compiler adds casts, type conversions, andsynthetic bridge methods as necessary to ensuretype-correct code.– Bridge methods are inserted into subtypes of

parameterized supertypes to ensure that subtypingworks as expected.

Page 19: Java Generics Introduction - Syntax Advantages and Pitfalls

19

Erasure Example...// Pre-Erasure (Notice the type variables)public void method() {

List<String> list = new ArrayList<String>();list.add("value");print(list);

}

// Pre-Erasure (Notice the type variables and omitted cast)

public void print(Collection<String> collection) {Iterator<String> it = collection.iterator();while (it.hasNext()) {

String element = it.next();

System.out.println(element);}

}

Page 20: Java Generics Introduction - Syntax Advantages and Pitfalls

20

Example Continued...// Post-Erasure (Erased generics)public void method() {

List list = new ArrayList();

list.add("value");print(list);

}

// Post-Erasure (Erased generics and inserted cast)

public void print(Collection collection) {String s;

for (Iterator it = collection.iterator(); it.hasNext();) {s = (String) iterator.next();System.out.println(s);

}}

Page 21: Java Generics Introduction - Syntax Advantages and Pitfalls

21

Type Parameters

Page 22: Java Generics Introduction - Syntax Advantages and Pitfalls

22

Multiple Type Parameters

• A generic type can accept more than one typevariable. For example, the Map interface acceptstwo variables. The first (K) defines the key typeand the second (V) defines the value type.

public interface Map<K,V> {V put(K key, V value);V get(Object key);

}

Map<String, String> map = new HashMap<String, String>();map.put("key", "value");String value = map.get("key");

Page 23: Java Generics Introduction - Syntax Advantages and Pitfalls

23

Passing Generics To Generics

• A generic type is itself a type that can be passedto another generic. Below is how you wouldcreate a list that holds a list of Strings.

List<String> listOfStrings = new ArrayList<String>();listOfStrings.add("value");

List<List<String>> listOfLists = new ArrayList<List<String>>();listOfLists.add(listOfStrings);

String value = listOfLists.get(0).get(0);

Page 24: Java Generics Introduction - Syntax Advantages and Pitfalls

24

Wildcard Arguments

• Wildcards are used to signify an unknown type.• Syntactically, wildcards are specified with <?>.

// List<?> is the pseudo-supertype of all lists

// It contains a list of unknown typespublic void printList(List<?> list) { // Type variables are always Objects for (Object element : list) { System.out.println(element);

}}

Question: What is the difference between List<?> and List<Object>?What would happen if we replaced the wildcard with Object?

Page 25: Java Generics Introduction - Syntax Advantages and Pitfalls

25

Wildcards Continued...

• Wildcard parameterized types are similar tointerfaces...– They can be declared, but no objects of a wildcard

parameterized type can be created.// Invalid instantiation attempt of a wildcard

List<?> list = new ArrayList<?>();

– They can refer to an Object that is of a type thatbelongs to a family of types the wildcard denotes.// Valid because Long extends Number (same family)List<? extends Number> list = new ArrayList<Long>();

// Wrong, String does not extend Number (not related)List<? extends Number> list = new ArrayList<String>;

Page 26: Java Generics Introduction - Syntax Advantages and Pitfalls

26

Bounded Types

Page 27: Java Generics Introduction - Syntax Advantages and Pitfalls

27

Bounded Types

• Used to restrict what can be passed to a genericby defining an upper or lower bound of a typevariable.

• Both upper and lower bounds are inclusive.• Bounds can be either a class or interface.

// The upper bound is an interfaceList<? extends Serializable>

// The lower bound is a class

List<? super Integer>

Page 28: Java Generics Introduction - Syntax Advantages and Pitfalls

28

Upper Bounds

• Upper bounds are defined as follows…<? extends superclass>

• The extends keyword was chosen because it isa reasonable approximation of the subtypeconcept, and the Java designers didn’t want toadd a new keyword to the language.

• The following accepts a Shape or any subclassof Shape such as Circle or Square.

// Shape is the upper bound

List<? extends Shape>

Page 29: Java Generics Introduction - Syntax Advantages and Pitfalls

29

Lower Bounds

• While not as useful, it is also possible to definethe lower bound of a type variable, by using thesuper keyword.

<? super subclass>

• The following will take a list of JDialogs or anyobject whose class is a superclass of JDialogsuch as Dialog or Window.

// JDialog is the lower bound

List<? super JDialog>

Page 30: Java Generics Introduction - Syntax Advantages and Pitfalls

30

Multiple Bounds

• Type variables can also have multiple bounds.• Use ampersands to separate bounded types.

<expression... class & interface & interface...>

• As with Java inheritance, there can be multipleinterfaces, but only one class, and it must be thefirst bound specified in the list of bounded types.

// Number is the only class and is listed first.

// The interfaces are randomly ordered.// Notice that T is passed to Comparable<T>.

<T extends Number & Comparable<T> & Serializable>

Page 31: Java Generics Introduction - Syntax Advantages and Pitfalls

31

Generic Methods AndConstructors

Page 32: Java Generics Introduction - Syntax Advantages and Pitfalls

32

Generic Methods

• Methods with type parameters are referred to asgeneric methods.

• They can exist within both generic classes andnon-generic classes.

• The scope of a method’s type parameter isrestricted to the method itself.

• Use when dependencies exist among the typesof one or more arguments and/or return type.

// The argument and return type are both of type Tpublic <T> T[] toArray(T[] a)

Page 33: Java Generics Introduction - Syntax Advantages and Pitfalls

33

Generic Methods Continued...

• Insert type variables between the modifiers andreturn type.

modifiers <typeVariables> returnType methodName(...)

• When calling a generic method, place the typearguments before the method name.

objectReference.<typeVariables>methodName();

Note: In most cases, you can omit the type parameters fromthe method call because the compiler will typically be ableto discern which method based on the actual typearguments.

Page 34: Java Generics Introduction - Syntax Advantages and Pitfalls

34

Generic Methods Continued...public class Collections {

public static <T> void copy(List<? super T> dest, List<? extends T> src) {...

}}

• T is a type variable or placeholder. It will bereplaced by the actual reference type passed asan argument to the generic method.

Collections.<Dialog>copy(windowList, jDialogList);Collections.copy(windowList, jDialogList);

Page 35: Java Generics Introduction - Syntax Advantages and Pitfalls

35

Generic Constructors

• Constructors with type parameters are referred toas generic constructors .

• They can exist within both generic classes andnon-generic classes.

• The scope of a constructor’s type parameter isrestricted to the constructor itself.

• Use when dependencies exist among the typesof one or more arguments.

• Just as with generic methods, type parameters ofgeneric constructors need not be providedexplicitly when invoked.

Page 36: Java Generics Introduction - Syntax Advantages and Pitfalls

36

Generic Classes AndInterfaces

Page 37: Java Generics Introduction - Syntax Advantages and Pitfalls

37

Custom Generic Classes

• Generic classes use the following syntax…

class className<typeParameters> {...

}

• Below is the syntax for declaring a reference to ageneric class.

className<typeArguments> variableName =

new className<typeArguments>(constructorArguments);

Note: See GenericExample class.

Page 38: Java Generics Introduction - Syntax Advantages and Pitfalls

38

Generic Interfaces

• As demonstrated earlier with List and Map,interfaces can also be generic.

public interface List<E> extends Collection<E> {boolean addAll(int index, Collection<? extends E> c);ListIterator<E> listIterator(int index);E set(int index, E element);

}

• The syntax is the same as with classes…

interface interfaceName<typeParameters> {...

}

Page 39: Java Generics Introduction - Syntax Advantages and Pitfalls

39

Generic Class Hierarchies

• The only difference between generic and non-generic hierarchies is that generic hierarchiesrequire type variables be passed up theinheritance tree accordingly.

• There are a few simple rules…– Generic classes can subclass other generic classes

and non-generic classes.– Non-generic classes cannot subclass generic classes.

• The reason is that a non-generic subclass cannot receivetype parameters and therefore cannot pass anything toits generic superclass.

– Subclasses are free to add their own parameters notrequired by the generic superclass.

Page 40: Java Generics Introduction - Syntax Advantages and Pitfalls

40

Generic Restrictions

• Type parameters cannot be instantiated.// Wrong! (Can’t create an instance of T)objectReference = new T();

• Static members cannot use a type parameterdeclared by the enclosing class.– However, you can declare static generic methods that

define their own type parameters.• A generic class cannot extend Throwable. This

means that you cannot create generic exceptionclasses.

Page 41: Java Generics Introduction - Syntax Advantages and Pitfalls

41

Restrictions Continued...

• It is not possible to instantiate an array whosebase type is a type parameter.– The reason is that T does not exist at runtime, so there

is no way for the compiler to know what type of array toactually create.

public class Generic<T extends Number> {

T[] array;Generic(T[] numbers) {

array = new T[10]; // Can’t create an array of Tarray = numbers; // Reference assignments are fine

}}

Page 42: Java Generics Introduction - Syntax Advantages and Pitfalls

42

Restrictions Continued...

• It is also not possible to create an array of type-specific generic references.– Arrays of specific generic types simply aren’t allowed

because they can lead to a loss of type safety.

// Wrong! (Type-specific generic references)Generic<Integer>[] array = new Generic<Integer>[10];

// Okay! (Wildcards are acceptable)

Generic<?>[] array = new Generic<?>[10];

Page 43: Java Generics Introduction - Syntax Advantages and Pitfalls

43

Legacy Conversion

Page 44: Java Generics Introduction - Syntax Advantages and Pitfalls

44

Converting Legacy To Generics

• Make certain that the generic API is not undulyrestrictive; it must continue to support the originalcontract of the API.

• You also need to ensure that the revised APIretains binary compatibility with old clients. Thisimplies that the erasure of the API must be thesame as the original, ungenerified API. In mostcases, this falls out naturally, but there are somesubtle cases.

Page 45: Java Generics Introduction - Syntax Advantages and Pitfalls

45

Generics In Context

Page 46: Java Generics Introduction - Syntax Advantages and Pitfalls

46

Generics In Context

• Because generics are such a fundamentalchange to the language, it’s important to have asolid understanding of them.

• Most interaction with generics will happen as aresult of using the collections framework.

• For the most part, application developers won’twrite a lot of custom generics, but will use thegenerics provided by various frameworks.

• The heavy writing of custom generics seems tobe most applicable for framework development.

Page 47: Java Generics Introduction - Syntax Advantages and Pitfalls

47

Drawbacks Of Generics

• Steep learning curve– Generics are a fundamental change and require a

completely different mindset.– Conceptually, generics can be difficult to grasp and

can lead to code that is difficult to read and follow.

• Added complexity– Many left C++ because of it’s complexity, some would

argue that Java is headed down that same road.– Much of Java’s original appeal was its simplicity. Some

believe that the trade-off for type safety is not worth theadded complexity introduced by generics.

Page 48: Java Generics Introduction - Syntax Advantages and Pitfalls

48

Summary

Page 49: Java Generics Introduction - Syntax Advantages and Pitfalls

49

Summary

• Generics are a powerful extension to the Javalanguage because they streamline the creation oftype-safe, reusable code.

• Within generics, automatic casting and typeconverting are provided by the compiler.

• The Collections framework has been entirelyreworked.– Now collections can be restricted and guaranteed to

only hold the specified type, passed as a parameter.– The need for type casting when retrieving an element

from a collection has been entirely eliminated.

Page 50: Java Generics Introduction - Syntax Advantages and Pitfalls

50

Summary Continued...

• Generics provide backward compatibility byenabling generic types to be used without typevariables (raw types).– It is strongly recommended; however, that new

applications avoid using raw types as future releasesof Java may not support them (according to the JavaLanguage Specification).

Page 51: Java Generics Introduction - Syntax Advantages and Pitfalls

51

Resources

Page 52: Java Generics Introduction - Syntax Advantages and Pitfalls

52

Additional Resources

• Tutorials– http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf– http://www.onjava.com/pub/a/onjava/2005/07/06/generics.html– http://www.informit.com/articles/article.asp?p=170176&seqNum=1

• Links– http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html– http://jcp.org/aboutJava/communityprocess/review/jsr014/– http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

• Books– Java 2 v5.0 (Tiger) New Features– Java 5.0 Tiger: A Developer's Notebook

Page 53: Java Generics Introduction - Syntax Advantages and Pitfalls

53

Discussion

Page 54: Java Generics Introduction - Syntax Advantages and Pitfalls

54

Open Discussion

• Questions?• Comments?• Donations?