1. Introduction
Generic programming means a code is written in terms of type which can be specified later and those types can be used as parameters. Generics in Java enabled us to use generic programming. But before generics, things were not that good. Let us explore examples without generics and see what issue would it have created.
2. Why was generics added to Java?
A type or method to operate on objects of various types while providing compile-time type safety.
https://docs.oracle.com/javase/1.5.0/docs/guide/language/index.html
https://en.wikipedia.org/wiki/Generics_in_Java
Prior to generics below is how you add names to List.
List names = new ArrayList(); names.add("Sansa"); names.add("Jon"); names.add("Arya"); names.add("Robb"); names.add("Bran"); names.add("Rickon"); // Can’t zig zag ;-)
How does this work? Well, ArrayList stores elements of type Object. Every class extends Object and hence you can insert any object into the ArrayList.
Access element from List.
String name = (String)names.get(0);
While retrieving an element we need to cast it because the element is stored is of type Object.
So what is the issue, you might think? Well you can insert element of any type i.e. above List can have Integer, Long, BigInteger, etc types in it.
List names = new ArrayList(); names.add("Sansa"); names.add("Jon"); names.add(new BigInteger("123")); names.add(Integer.valueOf(12345));
This List is perfectly valid because elements extend Object class. Now when we access the element from List we will run into runtime exception i.e. ClassCastException.
String name = (String)names.get(2); // throws ClassCastException.
There is no compile time type safety for this code. In order to provide compile time type safety and work with generic types it was important to add generics to Java.
In next article I will talk about how and why it was important to develop generics features in backward compatible way. This process is also called Generics Cast Guarantee.