Search⌘ K
AI Features

Solution: The Image Processor (PECS)

Explore how to apply the PECS (Producer Extends Consumer Super) principle in Java generics to design flexible, reusable image processing methods. Understand how to work with bounded wildcards to accept and manipulate lists of subclasses and superclasses, ensuring type safety while handling multiple image types like Jpeg and Png.

We'll cover the following...
Java 25
import java.util.ArrayList;
import java.util.List;
public class ImageProcessorSolution {
static class Image {
String filename;
public Image(String name) { this.filename = name; }
public String toString() { return "Image: " + filename; }
}
static class Jpeg extends Image {
public Jpeg(String name) { super(name); }
public String toString() { return "JPEG: " + filename; }
}
static class Png extends Image {
public Png(String name) { super(name); }
public String toString() { return "PNG: " + filename; }
}
// Generic method using PECS (Producer Extends, Consumer Super)
public static <T> void transferImages(List<? extends T> source, List<? super T> destination) {
for (T img : source) {
destination.add(img);
}
}
public static void main(String[] args) {
List<Jpeg> cameraRoll = new ArrayList<>();
cameraRoll.add(new Jpeg("photo.jpg"));
List<Png> scannerTray = new ArrayList<>();
scannerTray.add(new Png("scan.png"));
List<Image> processQueue = new ArrayList<>();
// T is inferred as 'Image'
// Works for Jpeg (Producer Extends Image)
transferImages(cameraRoll, processQueue);
// Works for Png (Producer Extends Image)
transferImages(scannerTray, processQueue);
System.out.println("Queue contains: " + processQueue);
}
}
...