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:
-
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 inObject). (Note: Java automatically upcasts the argument to theObjecttype when usingput.) -
You can potentially store values of different types in an instance of
IndexedList. However, this feature is generally undesirable. For example, suppose you have anIndexedListcalledapples. In this list, you want to store items of typeAppleand its subtypes likeMcIntoshRedandGoldenDelicious. Indeed, you do not want to store items of typeOrangeinapples.
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."