Java Reference
In-Depth Information
Using Generics
You will be tested on your knowledge of the generic versions of the Set , List , and Map
interfaces and implementation classes. You also need to understand the limitations of
nongeneric collection objects. Generics refers to a new feature added to J2SE 5.0 that
provides support for parameterized data types. Before J2SE 5.0, Collection objects
stored Object references, meaning that the compiler did not know the actual contents of
a collection. Generics provide compile-time type safety for collections by allowing your
Collection objects to specify what types they contain.
This section discusses generics and how to use them in collections, starting with a
discussion on the limitations of nongeneric collections.
Limitations of Nongeneric Collections
Let's look at an example that does not use generics to demonstrate the various limitations
of nongenerics. Suppose we create an ArrayList to contain String objects that represents
the keywords of the subject of this topic. The following code does not use generics and has
a problem. Do you see what the problem is?
7. ArrayList keywords = new ArrayList();
8. keywords.add(“java”);
9. keywords.add(“certification”);
10. keywords.add(“exam”);
11. keywords.add(new java.util.Date());
12.
13. for(Object x : keywords) {
14. String temp = (String) x;
15. System.out.println(temp.toUpperCase());
16. }
The ArrayList can contain any Object , even though we only want it to store String s.
Line 11 adds a Date object, which is a problem with nongenerics because the compiler
cannot stop us from putting a Date object in the ArrayList . Another problem is on line 14,
where each reference in the ArrayList is cast to a String so we can invoke toUpperCase .
The cast throws an exception when it gets to the Date object, as the following output
shows:
JAVA
CERTIFICATION
EXAM
Exception in thread “main” java.lang.ClassCastException: java.util.Date
cannot be cast to java.lang.String
Search WWH ::




Custom Search