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:

1. var names = List<String>();
2. names.addAll(['Seth', 'Kathy', 'Lars']);
3. 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:

1. abstract class ObjectCache {
2. Object getByKey(String key);
3. void setByKey(String key, Object value);
4. }

You discover that you want a string-specific version of this interface,so you create another interface:

1. abstract class StringCache {
2. String getByKey(String key);
3. void setByKey(String key, String value);
4. }

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:

1. abstract class Cache<T> {
2. T getByKey(String key);
3. void setByKey(String key, T value);
4. }

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.