Why use generics?
Generics are often required for type safety, but they have more benefitsthan just allowing your code to run:
- Properly specifying generic types results in better generated code.
- You can use generics to reduce code duplication.
If you intend for a list to contain only strings, you candeclare it as List<String>
(read that as “list of string”). That wayyou, your fellow programmers, and your tools can detect that assigning a non-string tothe list is probably a mistake. Here’s an example:
var names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
names.add(42); // Error
Another reason for using generics is to reduce code duplication.Generics let you share a single interface and implementation betweenmany types, while still taking advantage of staticanalysis. For example, say you create an interface forcaching an object:
abstract class ObjectCache {
Object getByKey(String key);
void setByKey(String key, Object value);
}
You discover that you want a string-specific version of this interface,so you create another interface:
abstract class StringCache {
String getByKey(String key);
void setByKey(String key, String value);
}
Later, you decide you want a number-specific version of thisinterface… You get the idea.
Generic types can save you the trouble of creating all these interfaces.Instead, you can create a single interface that takes a type parameter:
abstract class Cache<T> {
T getByKey(String key);
void setByKey(String key, T value);
}
In this code, T is the stand-in type. It’s a placeholder that you canthink of as a type that a developer will define later.