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)  
  1. list.add(1); - Not allowed
  2. 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)
  1. list.add(1); - Allowed
  2. 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

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)