bhylu.com

Advertisements

Java Read from Producers and Write to Consumers

Wildcard bounds describe which subtype relationships an operation can safely accept. Choose a bound from whether the method reads values, writes values, or does both.

Understand the idea

A List<? extends Number> can provide values known to be Numbers, but it cannot safely accept an arbitrary Integer or Double because its actual element type might be more specific. A List<? super Integer> can accept Integer values, while a retrieved element is only guaranteed to be an Object. The common producer-extends, consumer-super rule is a guide to the data flow, not a replacement for reasoning about each operation.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.List;
import java.util.ArrayList;

public class Main {
    static void appendCounts(List<? super Integer> target) { target.add(3); }
    static double sum(List<? extends Number> source) {
        double total = 0;
        for (Number value : source) total += value.doubleValue();
        return total;
    }

    public static void main(String[] args) {
        List<Number> collected = new ArrayList<>();
        appendCounts(collected);
        System.out.println(collected);
        System.out.println(sum(List.of(2, 5)));
    }
}

Expected output

[3]
7.0

The target can store an Integer even though it is declared as a list of Number. The source accepts integer elements and reads each through the Number contract. Converting everything to double is suitable for this demonstration, not a guarantee of exact decimal or large-integer arithmetic.

Check the official Java documentation for detailed contracts and supported options.