Lift the Limit with Java Generics!

Here is a plausible solution to make IndexedList ADT work for all types: change the data type of value from int to Object as in

void put(int index, Object value);
Object get(int index);

The potential issues with this approach are twofold:

  1. When you pass a value to put, Java automatically upcasts it to Object type. However, when you retrieve a value from get you must explicitly downcast it to its actual type (unless you only need to use the methods defined in Object).

  2. You can potentially store values of different types in an instance of IndexedList. This is generally undesirable: suppose you have an IndexedList called apples; while you want to store items of type Apple (and its subtypes like McIntoshRed, GoldenDelicious, ...) you do not want to store items of type Orange in apples.

Java, in 2004 within version J2SE 5.0, introduced Generics to address the shortcomings of the aforementioned strategy. According to Java's Documentation:

Generics extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety"

Generic programming is not specific to Java. Many other programming languages support a similar construct. In C++ for example, generics are supported and called "templates".