Problems With Type Erasure
Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure. For example, List
will be converted to the non-generic type List
, which ordinarily contains arbitrary objects. The compile-time check guarantees that the resulting code is type-correct.
As a result of type erasure, type parameters cannot be determined at run-time. For example, when an ArrayList
is examined at runtime, there is no general way to determine whether, before type erasure, it was an ArrayList
or an ArrayList
. Many people are dissatisfied with this restriction. There are partial approaches. For example, individual elements may be examined to determine the type they belong to; for example, if an ArrayList
contains an Integer
, that ArrayList was presumably parameterized with Integer
. Reflection can also determine the type parameter. However, no approach works in all cases.
Demonstrating this point, the following code outputs "Equal":
ArrayListJava generics differ from C++ templates. Java generics generate only one compiled version of a generic class or function regardless of the number of parameterizing types used. Furthermore, the Java run-time environment does not need to know which parameterized type is used because the type information is validated at compile-time and is not included in the compiled code. Consequently, instantiating a Java class of a parameterized type is impossible because instantiation requires a call to a constructor, which is unavailable if the type is unknown.
For example, the following code will not compile:
T instantiateElementType(ListBecause there is only one copy per generic class at runtime, static variables are shared among all the instances of the class, regardless of their type parameter. As a result, the type parameter cannot be used in the declaration of static variables or in static methods.
Read more about this topic: Generics In Java
Famous quotes containing the words problems with, problems and/or type:
“I was a wonderful parent before I had children. I was an expert on why everyone else was having problems with theirs. Then I had three of my own.”
—Adele Faber (20th century)
“I am always glad to think that my education was, for the most part, informal, and had not the slightest reference to a future business career. It left me free and untrammeled to approach my business problems without the limiting influence of specific training.”
—Alice Foote MacDougall (18671945)
“A cigarette is the perfect type of a perfect pleasure. It is exquisite, and it leaves one unsatisfied. What more can one want?”
—Oscar Wilde (18541900)