Collections and Generics – Generics

11.3 Collections and Generics

Before the introduction of generics in Java 1.5, a collection in the Java Collections Framework could hold references to objects of any type. For example, any object which is an instance of the java.lang.Object class or its subclasses could be maintained in an instance of the java.util.ArrayList class, which implements the java.util.List interface.

Click here to view code image

List wordList = new ArrayList();     // Using non-generic types.
wordList.add(“two zero two zero”);   // Can add any object.
wordList.add(2020);
//…
Object element = wordList.get(0);    // Always returns an Object.
//…
if (element instanceof String str) { // Runtime check to avoid ClassCastException.
  // Use reference str.
}

The client of a collection has to do most of the bookkeeping with regard to using the collection in a type-safe manner: which objects are put in the collection and how objects retrieved are used. Using the Object class as the element type allows the implementation of the collection class to be specific, but its use to be generic. An ArrayList is a specific implementation of the List interface, but usage of the class ArrayList is generic with regard to any object.

Using a generic collection, the compiler provides the type-safety, and the resulting code is less verbose.

Click here to view code image

List<String> wordList = new ArrayList<>();        // Using a specific type.
wordList.add(“two zero two zero”);                // Can add strings only.
wordList.add(2020);                               // Compile-time error!
//…
String element = wordList.get(0);                 // Always returns a String.
//…

Runtime checks or explicit casts are not necessary now. Generic types allow the implementation of the collection class to be generic, but its use to be specific. The generic type ArrayList<E> is a generic implementation of the List<E> interface, but now the usage of the parameterized type ArrayList<String> is specific, as it constrains the generic type ArrayList<E> to strings.

Leave a Reply

Your email address will not be published. Required fields are marked *