Limited to Integer Values?!
- Explain why we use generics in our ADT declaration.
Notice the IndexedList
ADT can only be used for integer values; the put
method takes in an integer, and the get
method returns an integer.
We asked students how we can make IndexedList
work with types other than the integer. Here are three interesting ideas they came up with:
-
Overload the
put
andget
methods for different data types. -
Use method overriding to provide multiple concrete implementations of
IndexedList
that work for different data types. -
Change the data type of value from
int
toObject
as invoid put(int index, Object value); Object get(int index);
Exercise Criticize each of the aforementioned ideas.
Solution
-
It's possible to overload
put
with different data types forvalue
. However, we cannot overloadget
by varying its return type because changing the return type is not enough for overloading. Furthermore, even if this was possible, we would only account for types already defined. In other words,IndexedList
will not work for programmer-defined types that it does not have an overloaded version of. Finally, assuming we knew all the data types in advance, this still would be an inelegant solution, to say the least, that would contain hundreds of overloaded methods. -
To override methods, the method's signature being overridden in a sub-class must be consistent with the overriding one in the parent class. So, we will not be able to override, e.g.,
put
in a sub-class and accept values of typeboolean
instead ofint
. -
This is by far the best idea and one which we used to employ (before Java had Generics -- soon to be explored!). Since every type (class) in Java is a subtype (sub-class) of
Object
, we can leverage type substitution and pass values of any type to theput
method and return it from theget
method. We will explore the potential issues with this strategy in the next lesson.
Let's answer a question you may have: how can one pass primitive types (int
, float
, char
, ...) to a method expecting Object
? The answer is: you cannot do that!! However, every primitive type in Java has a corresponding reference type! For example, int
has Integer
wrapper class that provides a way to use primitive type int
as an object.
Resources
You may find these resources helpful to familiarize yourself with wrapper classes in Java. In particular, it is useful to understand related concepts of Autoboxing and Unboxing):