Preface
Java now supports generics, the most significant change to the language since the addition of inner classes in Java 1.2—some would say the most significant change to the language ever.
Say you wish to process lists. Some may be lists of integers, others
lists of strings, and yet others lists of lists of strings. In Java before
generics this is simple. You can represent all three by the same class,
called List, which has elements of class
Object:
list of integers |
|
list of strings |
|
list of lists of strings |
|
In order to keep the language simple, you are forced to do some of the
work yourself: you must keep track of the fact that you have a list of
integers (or strings or lists of strings), and when you extract an element
from the list you must cast it from Object back to Integer (or String or List). For instance, the Collections Framework
before generics made extensive use of this idiom.
Einstein is reputed to have said, “Everything should be as simple as possible but no simpler”. And some might say the approach above is too simple. In Java with generics you may distinguish different types of lists:
list of integers |
|
list of strings |
|
list of lists of strings |
|
Now the compiler keeps track of whether you have a list of integers
(or strings or lists of strings), and no explicit cast back to Integer (or String or List<String>) is required. In some ways,
this is similar to generics in Ada or
templates in C++, but the actual inspiration is ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access