Java Generics
Today I discovered a feature of java that I have been using for a while but I didn’t know it existed. Generics allow developers to create generic algorithms that work on collections of different data types but at the same time provide type safety.
Generics are commonly used for data structures. List is an example of a data structure that uses generics:
1
List<String> list = new ArrayList<String>();
You could have declared your list like this:
1
List list = new ArrayList();
The difference is that by using generics you make sure that you don’t accidentally try to insert something that is not a string into your list and cause a run time error. By specifying in the list declaration that this is a List of Strings you make sure that you get a compile time error if you try to add something that is not a string to the list.