Download Java Generics: Understanding Type Constraints and Enforcement with Examples and more Study notes Computer Science in PDF only on Docsity!
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science
Java Generics
CMPSCI 220 (291A)
Programming Methodology
Spring 2009
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 2
Plan
Tutorial on Java Generics
Mostly follows the one on the web
Quick introduction the Effective Java items
Should read that chapter! It has many examples and
details we won’t talk about here
After this presentation:
You should be able to understand uses of generics in
Java libraries
You should be able to use them effectively yourself
(with additional practice)
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 3
Motivation: A Tiny Example
public class Box {
private Object object;
public void add (Object object) {
this.object = object;
public Object get() {
return object;
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 4
Using Box
// ONLY place Integer objects into
// this box!
Box integerBox = new Box();
integerBox.add(new Integer(10));
Integer someInteger =
(Integer)integerBox.get();
System.out.println(someInteger);
// Works; prints “10”
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 5
But what if some other code does:
integerBox.add("10");
// note how the type is now String
// then later:
Integer someInteger =
(Integer)integerBox.get();
System.out.println(someInteger);
// Oops! The cast fails … at run time
// Bad scene for the user!
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 6
What is the problem?
Cannot capture desired type constraint
So give the constraint of “Object”
Later code violates unstated – and
unenforced – constraint
What will help?
A way to state the constraint in the language
More importantly: enforcement of the constraint
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 7
Generics to the rescue!
// Generic version of the Box class.
public class Box {
private T t;
// T stands for "Type“
public void add (T t) {
this.t = t;
public T get() {
return t;
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 8
Using the generic Box class
Box integerBox =
new Box();
integerBox.add(new Integer(10));
Integer someInteger =
integerBox.get(); // no cast!
System.out.println(someInteger);
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 9
Type parameter name conventions
Single capital letter: makes it obvious that is it not a
regular class/interface name
Some common type parameter names:
E - Element (extensive in Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 10
Generic methods and constructors
public class Box {
public void inspect (U u){
System.out.println("T: " +
t.getClass().getName());
System.out.println("U: " +
u.getClass().getName());
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 11
Using the generic method
public class Box {
public static void main (String[] args) {
Box integerBox =
new Box();
integerBox.add(new Integer(10));
integerBox.inspect("some text");
// output:
// T: java.lang.Integer
// U: java.lang.String
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 12
Using the generic method (2)
integerBox.inspect(“xyz");
// can also write this as:
integerBox.inspect(“xyz”);
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 19
Subtype relationships for generics
Suppose S is a subtype of T.
Is Box a subtype of Box?
Consider:
Box bt = …;
Box bs = …;
bt.add(new T(…)); // works
bs.add(new T(…)); // should work – doesn’t!
So, you can’t use a bs everywhere you can use bt.
So Box is not a subtype of Box.
Usually true for any mutable generic type Xyz and Xyz.
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 20
Wildcard parameters
static void printNumberBox (Box b) {
System.output.println(b.get());
Box bi = …
printNumberBox(bi);
// fails:
// Box not subtype of Box
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 21
A generic printNumberBox
static void printNumberBox
(Box<? extends Number> b) {
System.output.println(b.get());
Box bi = …
printNumberBox2(bi);
// works!
// Box is subtype of
// Box<? extends Number>
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 22
Can do this the opposite way
class Foo {
boolean addTo (Collection<? super T> c) {
return c.add(this);
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 23
Sometimes you need to know about
the implementation: Type Erasure
// Compiler implements generics by erasing them
// The virtual machine knows nothing about them
public class MyClass {
@SuppressWarnings("unchecked")
public static void m (Object item) {
… item instanceof E … // Compiler error
E item2 = new E(); // Compiler error
E[] iArray = new E[10]; // Compiler error
E obj = (E)new Object();
// Unchecked cast warning: suppressed
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 24
EJ Item 23:
Don’t use raw types in new code
That is:
Use List, List, etc.,
not List (by itself).
Point: Better type-checking, fewer cases where
code blows up at run time.
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 25
EJ Item 24:
Eliminate uncheck warnings
Mostly this means to use proper type
parameters and constraints.
Sometimes this will be tricky, but the reward is
much more reliable code.
Use @SuppressWarnings(“unchecked”) only
when you really have to , and even then, carefully
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 26
EJ Item 25:
Prefer lists to arrays
Arrays do subtype checking at run time.
Generics do the checking at compile time.
Compile-time always wins for reliability.
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 27
EJ Item 26:
Favor generic types
Usually not to hard to generify your own types.
Makes your code more reusable.
Easier to do from the start.
Too bad Golden-T didn’t do it …
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 28
EJ Item 27:
Favor generic methods
Same arguments apply …
UU NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERSTMHERST •• Department of Computer ScienceDepartment of Computer Science 29
EJ Item 28:
Use bounded wildcards for flexibility
Example: Stack with
pushAll (Iterable src)
Better coded as:
pushAll (Iterable<? extends E> src)
Allows argument that is not exactly Iterable
U U NIVERSITY OFNIVERSITY OF MM ASSACHUSETTSASSACHUSETTS , A, A MHERST •MHERST• Department of Computer ScienceDepartment of Computer Science 30
EJ Item 29:
Consider typesafe mixed containers
Read the item ☺ …