Generic Collections

To elminate this problem, the collections framework was enhanced with the generics capabilities that we introduced with generic ArrayLists in Chapter 7 and that we discuss in more detail in Chapter 20, Generic Classes and Methods. Generics enable you to specify the exact type that will be stored in a collection and give you the benefits of compile-time type checking—the compiler issues error messages if you use inappropriate types in your collections. Once you specify the type stored in a generic collection, any reference you retrieve from the collection will have that type. This eliminates the need for explicit type casts that can throw ClassCastExceptions if the referenced object is not of the appropriate type. In addition, ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.