Generic Methods

Lab Java Intermediate 20 points

Write static <T> void printAll(List<T> items) and static <T> T lastOf(List<T> items). Read words and numbers into two lists and use both methods on each.

Input

Line 1: words. Line 2: integers.

Output

Four lines.

Example

Input

red green blue
1 2 3

Output

red | green | blue
blue
1 | 2 | 3
4
Sample input available Sample output available
Editor
Java

Hints

Put <T> before the return type to declare a generic method.

Solution explanation

The compiler infers T from the argument at each call.

Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    static <T> void printAll(List<T> items) {
        StringBuilder sb = new StringBuilder();
        for (T item : items) {
            sb.append(sb.length() > 0 ? " | " : "").append(item);
        }
        System.out.println(sb);
    }

    static <T> T lastOf(List<T> items) {
        return items.get(items.size() - 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<String> words = new ArrayList<String>();
        for (String w : sc.nextLine().trim().split("\\s+")) {
            words.add(w);
        }
        List<Integer> nums = new ArrayList<Integer>();
        for (String t : sc.nextLine().trim().split("\\s+")) {
            nums.add(Integer.parseInt(t));
        }
        printAll(words);
        System.out.println(lastOf(words));
        printAll(nums);
        System.out.println(lastOf(nums) + 1);
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD