Java Reference
In-Depth Information
Knowing about raw types helps you understand limitations of Java generics. For
example, you cannot replace type variables with primitive types. Erasure turns type
variables into the bounds type, such as Object or Comparable . The resulting
types can never hold values of primitive types.
To interface with legacy code, you can convert between generic and raw types.
Raw types are necessary when you interface with legacy code that was written before
generics were added to the Java language. For example, if a legacy method has a
parameter ArrayList (without a type variable), you can pass an
ArrayList<String> or ArrayList<BankAccount> . This is not completely
safeȌafter all, the legacy method might insert an object of the wrong type. The
compiler will issue a warning, but your program will compile and run.
780
781
S ELF C HECK
9. What is the erasure of the print method in Section 17.3 ?
10. What is the raw type of the LinkedList<E> class in Section 17.2 ?
C OMMON E RROR 17.2: Writing Code That Does Not
Work After Types Are Erased
Generic classes and methods were added to Java several years after the language
became successful. The language designers decided to use the type erasure
mechanism because it makes it easy to interface generic code with legacy
programs. As a result, you may run into some programming restrictions when you
write generic code.
For example, you cannot construct new objects of a generic type. For example, the
following method, which tries to fill an array with copies of default objects, would
be wrong:
public static <E> void fillWithDefaults(E[] a)
{
for (int i = 0; i < a.length; i++)
a[i] = new E(); // ERROR
}
Search WWH ::




Custom Search