Quiz: Explicit compile time generic type inference hints in Java

If you’ve been reading what I’ve been reading then you’ll know all about this but if you haven’t then relish this. Treat it as an exercise and see if you can answer the questions below without running the example.

Union method

public class Union {
    public static <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2) {
        Set<E> result = new HashSet<E>(s1);
        result.addAll(s2);
        return result;
    }
}

Usage 1: Will this compile and/or generate a warning?

public static void main(String... args) {
    Set<String> guys = new HashSet<String>(Arrays.asList("Tom", "Dick", "Harry"));
    Set<String> stooges = new HashSet<String>(Arrays.asList("Larry", "Moe", "Curly"));
    Set<String> aflCio = Union.union(guys, stooges);
    System.out.println(aflCio);
}

Usage 2: Will this compile and/or generate a warning?

public static void main(String... args) {
    Set<Integer> integers = new HashSet<Integer>(Arrays.asList(1, 2, 3));
    Set<Double> doubles = new HashSet<Double>(Arrays.asList(1d, 2d, 3d));
    Set<Number> numbers = Union.union(integers, doubles);
    System.out.println(numbers);
}

Usage 3: Will this compile and/or generate a warning?

public static void main(String... args) {
    Set<Integer> integers = new HashSet<Integer>(Arrays.asList(1, 2, 3));
    Set<Double> doubles = new HashSet<Double>(Arrays.asList(1d, 2d, 3d));
    Set<Number> numbers = Union.<Number> union(integers, doubles);
    System.out.println(numbers);
}

I’ll post the answer in a few days with an explanation and the source of this material. Have fun!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s