Java Generic - vinhtbkit/bkit-kb GitHub Wiki
- Code reuse
- Type safety
- Better performance
class GenericClass<T > {
T element;
}
<T> void genericMethod(List<T> list) {
}
<T1, T2> void genericMethod(T1 a, T2 b) {
}
Represent an unknown type
void test(List<?> lst) {
lst.foreach(e -> System.out.println(e));
}
interface Animal {
void run();
}
void test(List<? extends Animal> lst) {
lst.foreach(a -> a.run()));
}
static <T extends Comparable<Object>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
interface Person{}
interface Employee extends Person {}
public static void save(List<? super Person> list) {
// save
list.forEach(e -> {
// save
});
}
save(objectList); // valid
save(personList); // valid
save(employeeList); // invalid
- Producer Extends, Consumer Super
- If you need to retrieve (produce) items from a structure, use <? extends T>
- If you need to insert (consume) items into a structure, use <? super T>
static <T> void doSomething(T... args) {
Object[] objectArray = args; // Valid
objectArray[0] = "I don't fit in"; // ArrayStoreException
}