Skip to content
CalebLee edited this page Oct 13, 2021 · 2 revisions

Java has generic types, and we can make use of them too!

ArrayList<Integer> intList = new ArrayList<>();
ArrayList<String> strList = new ArrayList<>();
ArrayList<Object> objList = new ArrayList<>();

Making an object with a generic type is good for reusability where the same object can be used in different situations, just with the type of some fields being different.

To appreciate how generic types can make creating similar subclasses alot more convenient, let's suppose we want to implement a DogList of Dogs and a CatList of Cats (where Dog and Cat inherit from Animal), with tasks delegated to an internal ArrayList, similar to Lecture 8. You could implement them separately:

class DogList<Dog> {
    private final ArrayList<Dog> dogList;
    DogList() {
        this.dogList = new ArrayList<Dog>();
    }
    DogList<Dog> add(Dog dog) {
        this.dogList.add(dog);
        return this;
    }
}

class CatList<Cat> {
    private final ArrayList<Cat> catList;
    CatList() {
        this.catList = new ArrayList<Cat>();
    }
    CatList<Cat> add(Cat cat) {
        this.catList.add(cat);
        return this;
    }
}

But this would quickly get pretty tedious if you intended to implement a MouseList for Mouse, ElephantList for Elephant, etc. And even more tedious if we wanted to include more methods (apart from add). We can thus merge their similarities into a generic class, and have them extend the generic class as follows:

class AnimalList<T extends Animal> {
    private final ArrayList<T> animalList;
    AnimalList() {
        this.animalList = new ArrayList<T>();
    }
    AnimalList<T> add(Animal animal) {
        this.animalList.add(animal);
        return this;
    }
}

class CatList extends AnimalList<Cat> {
    CatList() {
        super();
    }

    @Override //If you want to return a CatList instead of a more general AnimalList
    CatList add(Cat cat) {
        super.add(cat);
    }
}
Clone this wiki locally