Generics and Collections
A good reference
Maurice Naftalin et
Philip Wadler
Java Generics
and
Collections
O'Reilly 2006
The Java tutorial
Generics
Collections
Generics
- Example0.java
: commented lines are refused by the compiler.
- you cannot add a double into a set of integers
- An Integer is an Object, but a Set<Integer> is not a
Set<Object> ! More genreally, if B extends A, an
instance of B is an instance of A, but a Set<B> is not a
Set<A>. A good reason is that if a is an instance of A,
but not of B, you may add a in the Set<A> but not in the
Set<B>.
- If you need to manipulate a Set without knowing the type of
its objects, you may use a joker (denoted by "?") :
Set<?>. But in that case, you cannot add any object in
that Set. The use of this joker is also necessary to provide a
method which allows to print all the element of a Set, without
knowing the type of its elements
- Container.java
: an example of generic class
- Example2.java
: example of use of the operator '<>' (Diamond).
- Example3.java
: example of use of '<? extends A>'.
- Example4.java,
MyClass.java,
MySubClass.java
: example of use of the operator '<? super A>'.
The example Iterators
This example uses the following classes : a class Iterators
which provides useful methods on instances of Iterator, an interface
Predicate
which declares a boolean method making it possible to test
predicates
on
objects, and a class TestIterators
for testing.