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
putandgetmethods for different data types. -
Use method overriding to provide multiple concrete implementations of
IndexedListthat work for different data types. -
Change the data type of value from
inttoObjectas invoid put(int index, Object value); Object get(int index);
Exercise Criticize each of the aforementioned ideas.
Solution
-
It's possible to overload
putwith different data types forvalue. However, we cannot overloadgetby 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,IndexedListwill 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.,
putin a sub-class and accept values of typebooleaninstead 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 theputmethod and return it from thegetmethod. 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):