Java Reference
In-Depth Information
at GenericsDemo.main(GenericsDemo.java:14)
We could use
instanceof
to avoid this situation, but that adds yet another step of
complexity to what should be a fairly simple task. Now let's look at this example again,
except we will use generics to specify the data type of the elements in the
ArrayList
.
As of J2SE 5.0, the class declaration of
ArrayList
is
public class ArrayList<E>
The
<E>
represents a generic element. The
E
is not required and can be any variable
name, but the naming convention for generics uses single uppercase letters to denote
generic types, and
E
is commonly used for elements. The
<E>
denotes that an
ArrayList
can
specify a data type when it is constructed. For example, the following code instantiates an
ArrayList
for
String
objects:
18. ArrayList<String> keywords2 = new ArrayList<String>();
19. keywords2.add(“java”);
20. keywords2.add(“certification”);
21. keywords2.add(“exam”);
22. keywords2.add(new java.util.Date());
The
ArrayList
of
keywords2
can only contain
String
objects, and the compiler enforces
this rule. Lines 19-21 compile fi ne, but line 22 generates the following compiler error:
GenericsDemo.java:22: cannot find symbol
symbol : method add(java.util.Date)
location: class java.util.ArrayList<java.lang.String>
keywords2.add(new java.util.Date());
The
add
method of
ArrayList
only accepts
String
references. Notice how generics allow
issues like this one to be discovered at compile time. The other benefi t of generics is that
you do not need to cast the data when accessing elements in the collection. For example,
any time an element in
keywords2
is accessed, it is returned as a
String
:
for(String keyword : keywords2) {
System.out.println(keyword.toUpperCase());
}
No casting appears in the code, which improves both the readability and reliability of
the code. A
ClassCastException
is not possible in the
for-each
loop, demonstrating how
generics and
for-each
loops work together to simplify working with collections.
Generics have greatly improved the Java Collections Framework. Generics allow the
compiler to enforce the data types that can be added to a collection, as well as retrieve
elements from the collection in their appropriate data type. Your Java code is simpler and
easier to read. Now that we have seen an example of generics, let's discuss what you need
to know about using generics with lists, sets, and maps.
Search WWH ::
Custom Search