Today we started our discussion of Java generics. I motivated generics by showing Friday’s source code, which used Object... p
varargs, and where p[0]
had to be an IListFactory
and p[1]
an IList
. Confusing the indices or passing the wrong value would lead to a ClassCastException
.
We then looked at how to make a Box<E>
, a wrapper that could contain any kind of value, but you had to specify its type. Later we worked out on the board what a generic ILambda
would look like, including an Equals
example that compared two Integer
values. Then we made another Equals<P>
that could compare any two values of the same type, so we specified one of the type variables of ILambda<R,P>
, but left the other one open.
The last thing I mentioned was that SpecialBox<Integer>
was a subclass of Box<Integer>
when SpecialBox<E> extends Box<E>
, but I’ll have to revisit that again, because the important thing is that Box<Integer>
is not a subtype of Box<Object>
even though Integer
is a subtype of Object
.
We also ran into an interesting problem with boxing when we write Equals
: p[0]
and p[1]
are Integers
, so p[0]==p[1]
does an identity comparison, not an integer equality test, so we had to do p[0].equals(p[1])
, but that lead well to the exercise Equals<P>
.
I also wasn’t sure about whether primitive types could be used in generics; I correctly said no, but I wasn’t sure, so I’ll reiterate that. I’m pretty happy with this lecture. We’ll see how well my students understood the concepts, because on Friday we’ll talk about upper and lower bounds and wildcards.