-
Notifications
You must be signed in to change notification settings - Fork 4
Generic Types T
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);
}
}
Peer Learning
Guides
Setting Up Checkstyle
Setting Up Java
Setting Up MacVim
Setting Up Stu
Setting Up Unix For Mac
Setting Up Unix For Windows
Setting Up Vim
Setting up SSH Config
SSH Without Password
Copying Files From PE Nodes
Using tmux
CS2030 Contents
Lecture 1 SummaryLecture 2 Summary
Access Modifiers
Lecture 3 Summary (Polymorphism)
Compile Time Type VS Runtime Type
Abstraction, Encapsulation, Inheritance, and Polymorphism
SOLID Principles
Class VS Abstract Class VS Interface
Comparable VS Comparator
Generic Types T
HashMap
Raw Types with Generic
Lambda expression
PECS (Producer Extends Consumer Super)
Optional
Streams
Parallel Streams
Monad
Functors and Monads with Category Theory