Java Reference
In-Depth Information
The type that you supply replaces the type variable in the interface of the class. For
example, the add method for ArrayList<BankAccount> has the type variable E
replaced with the type BankAccount :
public void add( BankAccount element)
Contrast that with the add method of our LinkedList class:
public void add(Object element)
The ArrayList methods are safer. It is impossible to add a String object into an
ArrayList<BankAccount> , but you can add a String into a LinkedList
that is intended to hold bank accounts.
ArrayList<BankAccount> accounts1 = new
ArrayList<BankAccount>();
LinkedList accounts2 = new LinkedList(); // Should
hold BankAccount objects
accounts1.add(Ðmy savingsÑ); // Compile-time error
accounts2.add(Ðmy savingsÑ); // Not detected at
compile time
The latter will give you grief when some other part of the code retrieves the string,
believing it to be a bank account:
BankAccount account = (BankAccount)
accounts2.getFirst(); // Run-time error
Code that uses the generic ArrayList class is also easier to read. When you spot an
ArrayList<BankAccount> , you know right away that it must contain bank
accounts. When you see a LinkedList , you have to study the code to find out what
it contains.
Type variables make generic code safer and easier to read.
In Chapters 15 and 16 , we used inheritance to implement generic linked lists, hash
tables, and binary trees, because you were already familiar with the concept of
inheritance. Using type variables requires new syntax and additional techniquesȌ
those are the topic of this chapter.
Search WWH ::




Custom Search