BM Balmiki Mandal 06 May 2023 9 views 0 comments Core Java

Java Generics PECS – Producer Extends Consumer Super

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.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023