Member-only story
Effective Java! Favor Generic Types
Using a generic type in our declarations is quite simple. The next step is allowing generics to be used in the types we create ourselves. Let us consider the following class that doesn’t use generics:
// Simple stack
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16; public Stack() {
elements = new Object[DEFAULT_INTITIAL_CAPACITY];
} public void push(Object e) {
ensureCapacity();
elements[size++] = e;
} public Object pop() {
if (size == 0) {
throw new EmptyStackException();
}
Object result = elements[--size];
elements[size] = null;
result result;
} public boolean isEmpty() {
return size == 0;
} private void ensureCapacity() {
if(elements.length == size) {
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
}
This class will definitely work but it’s not very convenient nor safe to use. In order to get anything productive done with this class we need to cast all accesses which can make our code less clear as well as can lead to accidents with type management. Never fear, we can simply generify this and fix these problems. Let’s take a look. The main thing we need to do is replace all places we mention Object
with E
as well as call out the generic type in the class declaration.
// Simple stack
public class Stack<E> {…