I have a static utility method named toSet() which receives objects and returns a Set.
public static <T> Set<T> toSet(T item, T... otherItems) {
Set<T> items = new HashSet<T>();
items.add(item);
items.addAll(Arrays.asList(otherItems));
return items;
}
The method works fine with other object but will yield compilation when I want to make a Set of Class<?>.
Set<String> strings = toSet("OK", "This works well", "No problem");
Set<Integer> numbers = toSet(1, 2, 3, 4, 5);
but
Class<?> test = String.class;
Set<Class<?>> entities = toSet(test);
will yield Type mismatch: cannot convert from Set<Class<capture#5-of ?>> to Set<Class<?>>.
Am I doing something wrong here? How can I achieve this without casting?
It looks like type inference breaks down in this case, for reasons someone else can hopefully explain. Casting isn’t necessary – just specify the type parameter explicitly: