Below is my working code written as an exercise in wildcards in generics and Java 8 type inference. My question will be about the commented line in union()
method.
I needed to create an instance of the interface type that does not include a static factory, so I was left with (seemingly) two choices:
- Use concrete implementation (as in my code below)
- Use Reflection to retrieve the actual run-time class and call its constructor (similar to my earlier question).
I chose to use the first approach and used a constructor of a concrete class HashSet<E>
(that implements Set
). I picked HashSet
among other publicly available implementations rather arbitrarily.
My reasoning was that any would suffice, since it will be returned by a method as just Set<E>
and, though it will retain its HashSet-specific
members, they will not interfere with a client process.
Was my decision safe and sound or is there a legitimate way to break my method code?
import java.util.*;
public class TypeInference {
public static <E> Set<E> union (Set<? extends E> s1, Set<? extends E> s2) {
Set<E> result = new HashSet<E>(); // or any other concrete Set
result.addAll(s1);
result.addAll(s2);
return result;
}
public static void main(String[] args) {
Set<Integer> ints = new TreeSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Double> doubles = new TreeSet<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0));
Set<Number> numbers = union(ints, doubles);
System.out.println(numbers);
}
}
union
supposed to return a set of the same subtype as s1? as s2? any set? should it throw an exception if s1 and s2 don't have the same type? Is the method supposed to retain the original order (if there is one)? Or work based on iteration order over s1 and s2? etc. Once you know exactly what the method needs to do, answering your question will be easy. \$\endgroup\$incompatible types
error (as it did at some point according to Josh Bloch's talk (around 31:23). \$\endgroup\$result
. And this is what my question is about. The rest was just the explanation why I wrote all this code. \$\endgroup\$