Bounded Wildcards PECS Generic Methods

Apply producer extends consumer super bounds to generic methods so a single helper reads from and fills any compatible list.

JavaData Integrity

Code

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

public class PecsCopy {

    // Producer Extends:只读 src,元素按 Number 消费
    static double sum(List<? extends Number> src) {
        double total = 0;
        for (Number n : src) {
            total += n.doubleValue();
        }
        return total;
    }

    // Consumer Super:只写 dst,可写入任何 Integer 的超类集合
    static void fillSquares(int count, List<? super Integer> dst) {
        for (int i = 1; i <= count; i++) {
            dst.add(i * i);
        }
    }

    public static void main(String[] args) {
        List<Integer> ints = List.of(1, 2, 3);
        List<Double> doubles = List.of(0.5, 1.5);
        System.out.println("sum(ints)=" + sum(ints));
        System.out.println("sum(doubles)=" + sum(doubles));

        List<Number> sink = new ArrayList<>();
        fillSquares(4, sink);
        System.out.println("sink=" + sink);
    }
}

Inside the snippet

Count the class PecsCopy and the functions sum, fillSquares and main as the entire surface area of Bounded Wildcards PECS Generic Methods.

Repetition is confined to for (Number n : src) — the rest of the file is straight-line.

Putting it to use

Entry signature: static double sum(List<? extends Number> src)

Look for the sum(ints)=, sum(doubles)=, sink= prefixes when the file runs; they tie each line to its step.

There are 2 calls inside main — sum and fillSquares — executed top to bottom.

Core lines

total += n.doubleValue();

Interactive Tools for This Topic

FAQ

What does Bounded Wildcards PECS Generic Methods print when run?
No setup needed: run the file and look for labeled lines like `sum(ints)=`, `sum(doubles)=`, `sink=` in the output.