October 22, 2018
Hot Topics:

Catch Errors at Compile Time with Java Generics

  • July 28, 2009
  • By Sridhar M S
  • Send Email »
  • More Articles »

Code Readability

The following are examples of declaring objects to hold data:

//dataList will hold objects of type integer
List dataList = new ArrayList<Integer>(); 
//dataList will hold objects of type string
List dataList = new ArrayList<String>(); 
//dataList will hold objects of type MyObject
List dataList = new ArrayList<MyObject>();

The introduction of generics has greatly improved code readability. Anyone who uses the code understands what types of inputs are essential for the integration efforts. For example, when Listing 3 is rewritten as Listing 4 below, the compiler throws errors during compilation.

Listing 4: Code Using Generics and Has an Exception
import java.util.*;
public class GenericsWithExp
    public static void main(String args[])
       GenericsWithExp genericsWithExp = new GenericsWithExp();
    private void initialize()
       List<Integer> dataList = new ArrayList<Integer>(); 
//Creating a new ArrayList to hold integers. //Even though the intention is to hold integer types,
//there is no place to explicitly specify this dataList.add(new String("5")); //Adding a String object Integer value = dataList.iterator().next();
//Retrieving the next value and assigning accordingly System.out.println("Retrieved value: "+value); } }

The compilation of Listing 4 fails with the following error message.

Looking into the error, it is clear that you can add objects of type integer only. Errors like these make it easy for the developers to correct their mistakes.

Generics Wildcards

If you do not know what type of data your collection is holding, then you can use a wildcard (<?>) in the placeholder for generics to indicate that the data type is unknown.

Assuming you have an ArrayList that has elements of unknown data types, you can simply employ the wildcard and start using the ArrayList in your application. Typical usage will be something like Listing 5.

Listing 5: Generics Using Wild Cards
import java.util.*;
public class GenericsWithWildCard
    public static void main(String args[])
       GenericsWithWildCard genericsWithWildCard = new GenericsWithWildCard();
       List<Integer> intValueList = genericsWithWildCard.buildIntegerList();
       System.out.println("Sum of Integer arguments: " +(int)genericsWithWildCard.computeSum(intValueList));
       List<Double> doubleValueList = genericsWithWildCard.buildDoubleList();
       System.out.println("Sum of Double arguments: " +genericsWithWildCard.computeSum(doubleValueList));
    private List buildIntegerList()
       List<Integer> dataList = new ArrayList<Integer>();
       dataList.add(new Integer(12));
       dataList.add(new Integer(7));
       return dataList;
    private List buildDoubleList()
       List<Double> dataList = new ArrayList<Double>();
       dataList.add(new Double(11.4));
       dataList.add(new Double(6.3));
       return dataList;
    private double computeSum(List<? extends Number> valueListArg)
       double sum = 0;
       for (Object i : valueListArg)
            if(i instanceof Integer)
                        sum += (Integer) i;
            else if(i instanceof Double)
                        sum += (Double) i;
                        System.out.println("Not an valid Integer/Double argument: "+i);
       return sum;

If you look carefully, the computeSum() method takes an argument of List, which is of unknown type, extending Number. The method is used for achieving the same action for both types (integer and double) of arguments. Using the unknown type is a little tricky and may not be clear in all your use cases. See the generics documentation for more information.

Good programming does not mean that you need to use complex development techniques. The simple, easy-to-understand code that you can produce with generics will be maintainable by others, which can make everyone's life easier when issues arise while you're not on premise. Others can debug your code easily in your absence.

Code Download

  • Generics_ClassCastException.zip

    For Further Reading

  • Generics Documentation (from java.sun.com)

    About the Author

    Sridhar M S is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.

  • Page 2 of 2

    Comment and Contribute


    (Maximum characters: 1200). You have characters left.



    Enterprise Development Update

    Don't miss an article. Subscribe to our newsletter below.

    By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


    Thanks for your registration, follow us on our social networks to keep up-to-date