THINK FIRST·CODE LATER

← All labs

Wildcards: producer extends, consumer super

Problem

Write Wildcards with:

  • double sum(List<? extends Number> numbers) — reads from the list;
  • void addSquares(List<? super Integer> target, int n) — writes 1², 2², … n² into the list;
  • String describe(List<?> items) — 3 item(s), first = 1;
  • <T> int copy(List<? extends T> source, List<? super T> destination).

Input: n and n integers, m and m doubles, and a count of squares. main sums a List<Integer> and a List<Double>, adds squares to a List<Number> and a List<Object>, then copies both original lists into the List<Number>.

For the input

3 1 2 3 2 0.5 1.5 3

the program prints

sum of ints: 6.0
sum of doubles: 2.0
numbers after addSquares: [1, 4, 9]
copied 3 ints and 2 doubles into numbers
numbers: [1, 4, 9, 1, 2, 3, 0.5, 1.5]
sum of numbers: 22.0
ints: 3 item(s), first = 1
objects: 3 item(s), first = 1

Try sum(List<Number>) instead of the wildcard: why does sum(ints) stop compiling?

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d2-5-data-1.txt

3 1 2 3 2 0.5 1.5 3
What your program must print for d2-5-data-1.txt
sum of ints: 6.0
sum of doubles: 2.0
numbers after addSquares: [1, 4, 9]
copied 3 ints and 2 doubles into numbers
numbers: [1, 4, 9, 1, 2, 3, 0.5, 1.5]
sum of numbers: 22.0
ints: 3 item(s), first = 1
objects: 3 item(s), first = 1

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d2-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d2-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.