Motivation
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList
of type Object
. Then, it adds a String
to the ArrayList
. Finally, it attempts to retrieve the added String
and cast it to an Integer
.
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException
) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
Using generics, the above code fragment can be rewritten as follows:
ListThe type parameter String
within the angle brackets declares the ArrayList
to be constituted of String
(a descendant of the ArrayList
's generic Object
constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0)
is defined as String
by the code generated by the compiler.
Compiling the third line of this fragment with J2SE 5.0 (or later) will yield a compile-time error because the compiler will detect that v.get(0)
returns String
instead of Integer
. For a more elaborate example, see reference.
Here is a small excerpt from the definitions of the interfaces List
and Iterator
in package java.util
:
Read more about this topic: Generics In Java
Famous quotes containing the word motivation:
“Self-determination has to mean that the leader is your individual gut, and heart, and mind or were talking about power, again, and its rather well-known impurities. Who is really going to care whether you live or die and who is going to know the most intimate motivation for your laughter and your tears is the only person to be trusted to speak for you and to decide what you will or will not do.”
—June Jordan (b. 1939)