'Cannot infer type of Class<?>
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?
Solution 1:[1]
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:
Set<Class<?>> entities = MyClass.<Class<?>>toSet(test);
Solution 2:[2]
Try this way also :
Class<String> test = String.class;
Set<Class<String>> entities = toSet(test);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul Bellora |
| Solution 2 | Priyank Doshi |
