Generics Cast Guarantee

1. Introduction

In previous article I wrote about Introduction to Java Generics. In this article we will see what cast guarantee is. Cast guarantee mean that the implicit cast done by generics will never fail. Let’s take a deeper look at what that means.

2. Cast Guarantee

For instance let us take the following code (Java 1.5 or greater)

List<String> names = new ArrayList<String>();
names.add("String1");
names.add("String2");

String result = names.get(0) + " " + names.get(1);

System.out.println(result); // String1 String2

ArrayList<E> class implements List<E> interface. So we wrote

List<String> names = new ArrayList<String>();
  • Then we insert two strings into the list names.add(“String1”); names.add(“String2”);
  • After that we concat both the strings using “+” operator with blank space in between them

Now, before Java Generics (before Java 1.5) were introduced same code was written as

List names = new ArrayList();
names.add("String1");
names.add("String2");

String result = ((String) names.get(0))+" "+((String) names.get(1));

System.out.println(result); // String1 String2

The difference between both the piece of code is that before Java 5 we need to explicitly cast the elements and type parameters “<E>” were eliminated.

But the identical part is that the bytecode compiled from both the pieces of code is same. If it is List<String>, List<Integer> or List<List<Integer>> all of them are represented as List in run-time. The process erases the type parameters which is known as type erasure.

As we saw that we need to cast explicitly before Java 1.5, whereas generics does the same cast implicitly in compile time and hence there won’t be ClassCastException at run-time. The implicit cast added by generics will never fail. This is a cast guarantee provided to us.

Now the questions comes why compiler take List<String> as List? The reason is backward compatibility. Developers who developed code prior to Java 1.5 need not change their code according to the new syntax provided in Java 1.5. So at the bytecode level the code that uses generics and the code that doesn’t use generics looks altogether the same. So the developers need not shift their syntax overnight in order to use the features provided in Java 1.5.

Leave a Reply

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