Lift the Limit with Java Generics!

  • Translate the IndexedList ADT into a generic interface.
  • Identify the syntax of 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 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). (Note: Java automatically upcasts the argument to the Object type when using put.)

  2. You can potentially store values of different types in an instance of IndexedList. However, this feature is generally undesirable. For example, suppose you have an IndexedList called apples. In this list, you want to store items of type Apple and its subtypes like McIntoshRed and GoldenDelicious. Indeed, 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."