Generics - PECS; difference between Extends and Super
PECS - Producer Extends, Consumer Super
- Use extends when you get values out of a data structure
- Use Super when you put values into a data structure
- Use an explicit when you plan to do both
public static void testExtends(List<? extends Number> list)
- list.add(1); - Not allowed
- list.get(0); - Allowed
With extends, we can only extract the values and use them. Becaue, addition is not allowed inside the method.
public static void testSuper(List<? super Integer> output)
- list.add(1); - Allowed
- list.get(0); - Allowed
With Super, we can only supply the values. Because, if we write a functionality, it cannot be leveraged to its child classes. But, its diversity exists in accepting List<Integer>, List<Number> and List<Object> for both addition and retrieval.
Comments
Post a Comment