7.7. Generating Strongly Typed Collections

As a simple example of the performance tradeoffs that drive a GP design, consider the collection classes in the java.util package. The various collections (ArrayList, HashMap, etc.) are all of type Object—in other words, the collections are entirely generic. If you want to use a collection in a type-safe fashion, then you must write additional code to enforce type safety at runtime, as shown here:

// Must pay runtime cost of casting to String
// also possible that cast might fail
String value = (String) stack.pop();

One workaround to this problem is to write your own strongly typed collections, such as hand-coded StringStack, IntStack, and so on. Such work is tedious, error-prone, and better suited ...

Get Component Development for the Java™ Platform 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.