Why do generics exist in Java, and what problem do they actually solve?
Generics exist so that the compiler can check the types of what you put into a collection and what you take out of it.
Before generics, every collection held Object. You put anything into a list, and when you took something out you had to cast it yourself, and the compiler had no idea whether the cast was right. The mistake was only found when the program ran, and often a long way from the line that caused it.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// The list says what it holds, so the compiler checks it.
List<String> names = new ArrayList<String>();
names.add("Ada");
// This does not compile, because an Integer is not a String.
// names.add(42);
// And this one does not compile either, because the result
// of get is a String and cannot be given to an int.
// int length = names.get(0).length();
// With the old style of list, both of those mistakes were
// only found while the program was running.
List raw = new ArrayList();
raw.add("Ada");
String name = (String) raw.get(0);
System.out.println("the old way needs a cast : " + name);
}
}
So there are three things that generics buy you.
The first one is that the compiler catches the mistake before the program runs. The line that tries to add a number to a list of strings does not compile, and you find out about it straight away instead of at three in the morning.
The second one is that you do not need the cast. The result of taking something out of a list of strings is already a string, so there is nothing to convert and nothing to forget to convert.
The third one is that the error messages are useful. When the compiler says that a method wants a string and you have given it a number, it tells you which line and which argument, and it often suggests the fix.
The next question in this topic looks at how the type parameters are written.