Java Reference
In-Depth Information
cost that the customer now thinks less of our software and our company. So let's adopt techniques,
including generics, that catch errors early.
Listing 15-9 and Listing 15-10 demonstrate why generics promote early error detection.
Listing 15-8. An Ordinary List
List integerList = new LinkedList();
integerList.add(new Integer(0));
integerList.add("here's a problem"); // perfectly legal and very wrong
In listing 15-9,
integerList
can contain any object. I can pass objects of type
String
into that list. A
name is just a name and, while it reveals the intent (which is good practice), it doesn't offer any
protection against someone passing things other than objects of type
Integer
into the list. Consequently,
when someone does pass something other than an Integer object, we get a run-time error when we try to
get
Integer
objects out of this list.
So let's see how generics prevent the testers or, worse, the customer from ever seeing our error.
Listing 15-9. A Generic List
List<Integer> integerList = new LinkedList<Integer>();
integerList.add(new Integer(0));
integerList.add("here's a problem");
The generic expression (or parameter) on the
List
declaration in the second example specifies that
this list can contain only
Integer
objects. The
Integer
parameter prevents anyone from passing a
String
object (or anything but an
Integer
object) to
integerList
. When some other programmer tries to add an
object that isn't of type Integer to
integerList
, they get a compiler error. Their code can't be compiled,
and there's no chance the customer will ever see an error because some sloppy coder confuses a
String
with an
Integer
. Figure 15-1 shows the error that Eclipse produces when I try it.
Figure 15-1. Type match error from trying to misuse a generic list
Notice how it says the proper argument for the add method is an Integer object. The
List
interface
has no such method, in fact. However, the Eclipse compiler creates an instance of the
LinkedList
class
that has such a method. Consequently, no one can compile code that violates the intention of our
generic list. That prevents all the problems that might occur at run-time and prevents our fellow
programmers, the testers, and ultimately our customers from thinking we must be idiots.
Personally, I also find this kind of code to be easier to read and to write. Casting always feels like
clutter to me. Purist that I am, I also much prefer to have the proper type in the first place and not need
to cast.