How to use Java generics to avoid ClassCastExceptions

Learn how Java’s support for generics helps you develop more robust code

1 2 3 Page 2
Page 2 of 3
For a given subtype x of type y, and given G as a raw type declaration, G<x> is not a subtype of G<y>.

According to this rule, although String and java.lang.Integer are subtypes of java.lang.Object, it’s not true that List<String> and List<Integer> are subtypes of List<Object>.

Why do we have this rule? Remember that generics are designed to catch type-safety violations at compile time, which is helpful. Without generics, you are much more likely to be called in to work at 2 a.m. because your Java program has thrown a ClassCastException and crashed!

As a demonstration, let’s assume that List<String> was a subtype of List<Object>. If this was true, you might end up with the following code:

List<String> directions = new ArrayList<String>();
List<Object> objects = directions;
objects.add(new Integer());
String s = objects.get(0);

This code fragment creates a list of strings based on an array list. It then upcasts this list to a list of objects (which isn’t legal, but for now just pretend it is). Next, it adds an integer to the list of objects, which violates type safety. The problem occurs in the final line, which throws ClassCastException because the stored integer cannot be cast to a string.

You could prevent such a violation of type safety by passing an object of type List<Object> to the printList() method in Listing 3. However, doing so wouldn’t be very useful. Instead, you can use wildcards to solve the problem, as shown in Listing 4.

Listing 4: GenDemo.java (version 4)

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenDemo
{
   public static void main(String[] args)
   {
      List<String> directions = new ArrayList<String>();
      directions.add("north");
      directions.add("south");
      directions.add("east");
      directions.add("west");
      printList(directions);
      List<Integer> grades = new ArrayList<Integer>();
      grades.add(Integer.valueOf(98));
      grades.add(Integer.valueOf(63));
      grades.add(Integer.valueOf(87));
      printList(grades);
   }
   static void printList(List<?> list)
   {
      Iterator<?> iter = list.iterator();
      while (iter.hasNext())
         System.out.println(iter.next());
   }
}

In Listing 4 I use a wildcard (the ? symbol) in place of Object in the parameter list and body of printList(). Because this symbol stands for any type, it’s legal to pass List<String> and List<Integer> to this method.

Compile Listing 4 (javac GenDemo.java) and run the application (java GenDemo). You should observe the following output:

north
south
east
west
98
63
87

Discovering generic methods

Now say you want to copy a list of objects to another list subject to a filter. You might consider declaring a void copy(List<Object> src, List<Object> dst, Filter filter) method, but this method would only be able to copy Lists of Objects and nothing else.

To pass source and destination lists of arbitrary type, you need to use the wildcard for a type placeholder. For example, consider the following copy() method:

void copy(List<?> src, List<?> dest, Filter filter)
{
   for (int i = 0; i < src.size(); i++)
      if (filter.accept(src.get(i)))
         dest.add(src.get(i));
}

This method’s parameter list is correct, but there’s a problem. According to the compiler, dest.add(src.get(i)); violates type safety. The ? implies that any kind of object can be the list’s element type, and it’s possible that the source and destination element types are incompatible.

For example, if the source list was a List of Shape and the destination list was a List of String, and copy() was allowed to proceed, ClassCastException would be thrown when attempting to retrieve the destination list’s elements.

You could partially solve this problem by providing upper and lower bounds for the wildcards, as follows:

void copy(List<? extends String> src, List<? super String> dest, Filter filter)
{
   for (int i = 0; i < src.size(); i++)
      if (filter.accept(src.get(i)))
         dest.add(src.get(i));
}

You can provide an upper bound for a wildcard by specifying extends followed by a type name. Similarly, you can supply a lower bound for a wildcard by specifying super followed by a type name. These bounds limit the types that can be passed as actual type arguments.

In the example, you can interpret ? extends String as any actual type argument that happens to be String or a subclass. Similarly, you can interpret ? super String as any actual type argument that happens to be String or a superclass. Because String is final, which means that it cannot be extended, only source lists of String objects and destination lists of String or Object objects can be passed, which isn’t very useful.

You can fully solve this problem by using a generic method, which is a class or instance method with a type-generalized implementation. A generic method declaration adheres to the following syntax:

<formalTypeParameterList> returnType identifier(parameterList)

A generic method’s formal type parameter list precedes its return type. It consists of type parameters and optional upper bounds. A type parameter can be used as the return type and can appear in the parameter list.

Listing 5 demonstrates how to declare and invoke (call) a generic copy() method.

Listing 5: GenDemo.java (version 5)

import java.util.ArrayList;
import java.util.List;
public class GenDemo
{
   public static void main(String[] args)
   {
      List<Integer> grades = new ArrayList<Integer>();
      Integer[] gradeValues = 
      {
         Integer.valueOf(96),
         Integer.valueOf(95),
         Integer.valueOf(27),
         Integer.valueOf(100),
         Integer.valueOf(43),
         Integer.valueOf(68)
      };
      for (int i = 0; i < gradeValues.length; i++)
         grades.add(gradeValues[i]);
      List<Integer> failedGrades = new ArrayList<Integer>();
      copy(grades, failedGrades, new Filter<Integer>()
                                 {
                                    @Override
                                    public boolean accept(Integer grade)
                                    {
                                       return grade.intValue() <= 50;
                                    }
                                 });
      for (int i = 0; i < failedGrades.size(); i++)
         System.out.println(failedGrades.get(i));
   }
   static <T> void copy(List<T> src, List<T> dest, Filter<T> filter)
   {
      for (int i = 0; i < src.size(); i++)
         if (filter.accept(src.get(i)))
            dest.add(src.get(i));
   }
}
interface Filter<T>
{
   boolean accept(T o);
}

In Listing 5 I’ve declared a <T> void copy(List<T> src, List<T> dest, Filter<T> filter) generic method. The compiler notes that the type of each of the src, dest, and filter parameters includes the type parameter T. This means that the same actual type argument must be passed during a method invocation, and the compiler infers this argument by examining the invocation.

If you compile Listing 5 (javac GenDemo.java) and run the application (java GenDemo) you should observe the following output:

27
43

Generics and type inference

The Java compiler includes a type inference algorithm for identifying the actual type argument(s) when instantiating a generic class, invoking a class’s generic constructor, or invoking a generic method.

Generic class instantiation

Before Java SE 7, you had to specify the same actual type argument(s) for both a variable’s generic type and the constructor when instantiating a generic class. Consider the following example:

Map<String, Set<String>> marbles = new HashMap<String, Set<Integer>>();

The redundant String, Set<String> actual type arguments in the constructor invocation clutter the source code. To help you eliminate this clutter, Java SE 7 modified the type inference algorithm so that you can replace the constructor’s actual type arguments with an empty list (<>), provided that the compiler can infer the type arguments from the instantiation context.

Informally, <> is referred to as the diamond operator, although it isn’t a real operator. Use of the diamond operator results in the following more concise example:

Map<String, Set<String>> marbles = new HashMap<>();

To leverage type inference during generic class instantiation, you must specify the diamond operator. Consider the following example:

Map<String, Set<String>> marbles = new HashMap();

The compiler generates an “unchecked conversion warning” because the HashMap() constructor refers to the java.util.HashMap raw type and not to the Map<String, Set<String>> type.

Generic constructor invocation

Generic and non-generic classes can declare generic constructors in which a constructor has a formal type parameter list. For example, you could declare the following generic class with a generic constructor:

public class Box<E>
{
   public <T> Box(T t) 
   {
      // ...
   }
}

This declaration specifies generic class Box<E> with formal type parameter E. It also specifies a generic constructor with formal type parameter T. Consider the following example:

new Box<Marble>("Aggies")

This expression instantiates Box<Marble>, passing Marble to E. Also, the compiler infers String as T’s actual type argument because the invoked constructor’s argument is a String object.

We can go further by leveraging the diamond operator to eliminate the Marble actual type argument in the constructor invocation, as long as the compiler can infer this type argument from the instantiation context:

Box<Marble> box = new Box<>("Aggies");

The compiler infers the type Marble for formal type parameter E of generic class Box<E>, and infers type String for formal type parameter T of this generic class’s constructor.

Generic method invocation

When invoking a generic method, you don’t have to supply actual type arguments. Instead, the type inference algorithm examines the invocation and corresponding method declaration to figure out the invocation’s type argument(s). The inference algorithm identifies argument types and (when available) the type of the assigned or returned result.

The algorithm attempts to identify the most specific type that works with all arguments. For example, in the following code fragment, type inference determines that the java.io.Serializable interface is the type of the second argument (new TreeSet<String>()) that is passed to select() — TreeSet implements Serializable:

Serializable s = select("x", new TreeSet<String>());
static <T> T select(T a1, T a2) 
{
   return a2;
}

I previously presented a generic static <T> void copy(List<T> src, List<T> dest, Filter<T> filter) class method that copies a source list to a destination list, and is subject to a filter for deciding which source objects are copied. Thanks to type inference, you can specify copy(/*...*/); to invoke this method. It’s not necessary to specify an actual type argument.

You might encounter a situation where you need to specify an actual type argument. For copy() or another class method, you would specify the argument(s) after the class name and member access operator (.) as follows:

GenDemo.<Integer>copy(grades, failedGrades, new Filter() /*...*/);

For an instance method, the syntax is nearly identical. Instead of following a class name and operator, however, the actual type argument would follow the constructor call and member access operator:

new GenDemo().<Integer>copy(grades, failedGrades, new Filter() /*...*/);

Criticism and limitations of generics in Java

While generics as such might not be controversial, their particular implementation in the Java language has been. Generics were implemented as a compile-time feature that amounts to syntactic sugar for eliminating casts. The compiler throws away a generic type or generic method’s formal type parameter list after compiling the source code. This “throwing away” behavior is known as type erasure (or erasure, for short). Other examples of erasure in generics include inserting casts to the appropriate types when code isn’t type correct, and replacing type parameters by their upper bounds (such as Object).

Erasure prevents a generic type from being reifiable (exposing complete type information at runtime). As a result, the Java Virtual Machine cannot tell the difference between, for example, Set<String> and Set<Marble>; at runtime, only the raw type Set is available. In contrast, primitive types, non-generic types (reference types prior to Java 5), raw types, and invocations of wildcards are reifiable.

The inability for generic types to be reifiable has resulted in several limitations:

1 2 3 Page 2
Page 2 of 3
How to choose a low-code development platform