9.1 The Problem of Generality

Recall the two list classes we created last week: SLList and AList. If you take a look at their documentation, you'll notice that they are very similar. In fact, all of their supporting methods are the same!

Suppose we want to write a class WordUtilsthat includes functions we can run on lists of words, including a method that calculates the longest string in an SLList.

Exercise 4.1.1. Try writing this method by yourself. The method should take in an SLList of strings and return the longest string in the list.

Here is the method that we came up with.

public static String longest(SLList<String> list) {
    int maxDex = 0;
    for (int i = 0; i < list.size(); i += 1) {
        String longestString = list.get(maxDex);
        String thisString = list.get(i);
        if (thisString.length() > longestString.length()) {
            maxDex = i;
        }
    }
    return list.get(maxDex);
}

How do we make this method work for AList as well?

All we really have to do is change the method's signature: the parameter

SLList<String> list

should be changed to

AList<String> list

Now we have two methods in our WordUtils class with exactly the same method name.

public static String longest(SLList<String> list)

and

public static String longest(AList<String> list)

This is actually allowed in Java! It's something called method overloading. When you call WordUtils.longest, Java knows which one to run according to what kind of parameter you supply it. If you supply it with an AList, it will call the AList method. Same with an SLList.

It's nice that Java is smart enough to know how to deal with two of the same methods for different types, but overloading has several downsides:

  • It's super repetitive and ugly, because you now have two virtually identical blocks of code.

  • It's more code to maintain, meaning if you want to make a small change to the longest method such as correcting a bug, you need to change it in the method for each type of list.

  • If we want to make more list types, we would have to copy the method for every new list class.

Last updated