Java Reference
In-Depth Information
fromthecontext,youcanomittheredundant Employee typenamefrombetween Ar-
rayList 's < and > characters, resulting in List<Employee> employees =
new ArrayList<>(); .
Note Becauseofitsappearance,manydevelopersrefertothe <> charactersequence
asthe diamond operator .Idon'tregard <> asatrueoperator,whichiswhyIdon'tin-
clude it in Table 1-3 's list of Java operators.
Also, Iterator<Employee> —youcannotusethediamondoperatorinthiscon-
text—indicates that iterator() returns an Iterator whose next() method re-
turns only Employee objects. It is not necessary to cast iter.next() 's returned
value to Employee because the compiler inserts the cast on your behalf.
If you attempt to compile this listing, the compiler will report an error when it en-
counters employees.add("Jack Frost"); . The error message will tell you
that the compiler cannot find an add(java.lang.String) method in the
java.util.List<Employee> interface.
Unlikeinthepre-generics List interface,whichdeclaresan add(Object) meth-
od, the generified List interface's add() method parameter reflects the interface's
parameterized type name. For example, List<Employee> implies
add(Employee) .
Listing 3-50 revealed that the unsafe code causing the ClassCastException
( employees.add("Jack Frost"); ) and the code that triggers the exception
( (Employee) iter.next() )arequiteclose.However,theyareoftenfartherapart
in larger applications.
Rather than having to deal with angry clients while hunting down the unsafe code
thatultimatelyledtothe ClassCastException ,youcanrelyonthecompilersav-
ingyouthisfrustrationandeffortbyreportinganerrorwhenitdetectsthiscodeduring
compilation.Detectingtypesafetyviolationsatcompiletimeisthebenefitofusinggen-
erics.
Generic Types
A generic type isaclassorinterfacethatintroducesafamilyofparameterizedtypesby
declaringa formal type parameter list (acomma-separatedlistof type parameter names
between angle brackets). This syntax is expressed as follows:
class identifier < formal_type_parameter_list > {}
interface identifier < formal_type_parameter_list > {}
Search WWH ::




Custom Search