Quiz: Explicit compile time generic type inference hints in Java

by Dhruba Bandopadhyay on Tue, 30 Dec 2008 00:04:46 +0000

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!

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: