Question
What are the distinctions between 'E', 'T', and '?' in Java generics?
public interface Foo<E> {}
public interface Bar<T> {}
public interface Zar<?> {}
Answer
In Java generics, 'E', 'T', and '?' are used to denote type parameters in generic classes and interfaces, each serving specific functions in providing type safety and flexibility in programming.
public interface GenericContainer<T> {
void add(T item);
T get(int index);
}
public void processItems(List<?> items) {
for (Object item : items) {
System.out.println(item);
}
}
Causes
- 'E' generally represents elements in a collection, primarily used in the context of collection frameworks like Lists and Sets.
- 'T' is a more general-purpose type parameter often used in various generic classes and methods.
- '?' signifies a wildcard type which means an unknown type, useful when you want a method or class to accept a variety of different types without specifying exactly what those types are.
Solutions
- Use 'E' when defining classes and interfaces intended for collections, like custom List implementations.
- Use 'T' when defining generic classes or methods where a specific type is not predetermined.
- Use '?' when you are okay with accepting any type as a parameter, particularly in method arguments to enhance flexibility.
Common Mistakes
Mistake: Using the wildcard '?' as a type parameter in a method where a specific type is needed.
Solution: Ensure to use a type parameter (e.g., 'T', 'E') when the method's functionality requires type specificity.
Mistake: Confusing the use of 'E' and 'T' as interchangeable without understanding their context.
Solution: Remember that 'E' is specifically for elements, mainly in collections, while 'T' can be used more broadly.
Helpers
- Java generics
- E T wildcard
- Java generic types
- difference between E and T in Java
- Java generic interfaces