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:
-
When you pass a value to
put, Java automatically upcasts it toObjecttype. However, when you retrieve a value fromgetyou must explicitly downcast it to its actual type (unless you only need to use the methods defined inObject). -
You can potentially store values of different types in an instance of
IndexedList. This is generally undesirable: suppose you have anIndexedListcalledapples; while you want to store items of typeApple(and its subtypes likeMcIntoshRed,GoldenDelicious, ...) 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".