Java Generics PECS – Producer Extends Consumer Super

06 May 2023 Balmiki Mandal 0 Core Java

What is PECS - Producer Extends Consumer Super?

PECS stands for Producer Extends, Consumer Super. It is a rule that applies to the use of generics in Java. The Producer Extends Consumer Super rule states that when you are dealing with generics, if you are using the generic type as a parameter to a method, the parameter should be declared as having an upper bound wildcard (extending a type) when it is an output parameter, and as having a lower bound wildcard (supering a type) when it is an input parameter.

Why is it important?

The importance of the PECS rule lies in ensuring type safety. By setting these boundaries, you can make sure that input parameters are of the correct type before being used, and that objects that are created as outputs from a method have the same type that you expect. This also ensures that unexpected results do not occur during run-time, which could lead to errors or unexpected behavior.

Examples

For example, if you have a method that creates a list of objects of a certain type:

public List<MyType> getObjectList() {
  // ...
}

You would write the declaration of the method as:

public List<? extends MyType> getObjectList() {
  // ...
}

This means that the list returned by the method will always contain objects of type MyType, or one of its descendants. Conversely, if you had a method whose argument was a list of objects of type MyType:

public void doSomethingWithList(List<MyType> list) {
  // ...
}

You would declare it as:

public void doSomethingWithList(List<? super MyType> list) {
  // ...
}

This ensures that the type of the objects contained in the list is compatible with MyType, or one of its ancestors.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.