Limited to Integer Values?!

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:

  1. Overload the put and get methods for different data types.

  2. Use method overriding to provide multiple concrete implementations of IndexedList that work for different data types.

  3. Change the data type of value from int to Object as in

    void put(int index, Object value);
    Object get(int index);
    

Exercise Criticize each of the aforementioned ideas.

Solution
  1. It's possible to overload put with different data types for value but we will not be able to overload get by varying its return type (because changing return type is not enough for overloading). Even if this was possible, we would only be able to 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. Assuming we knew all the data types in advance, this still would be an inelegant solution, to say the least, that would contain tens of overloaded methods.

  2. To override methods, the signature of the method being overridden in a subclass must be consistent with the overriding one in the parent class. So, we will not be able to e.g. override put in a subclass and have it accept values of type boolean instead of int.

  3. 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 (subclass) of Object, we can leverage type substitution and pass values of any type to the put method and return it from the get 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 useful to familiarize yourself with wrapper classes in Java (in particular, it is useful to understand related concepts of Autoboxing and Unboxing):