0

If we are only talking about Class, as in java.lang.Class, what is the real difference between, say

Map<Class<?>, Class<?>>

and

Map<Class, Class>

?

For other type names like List (which is not what this question is about at all), the wildcard makes a difference: you can't put something in a List<?> in a type safe manner. Since writing Map gives a compile warning yet I can still do map.put(Integer.class, String.class) on it, I was curious to know if it really does matter if Class or Class<?> gets used.

Would there be a real point to go through code that hasMap<String, Class> and replace it with Map<String, Class<?>, aside for the compiler warning?

Christian Neverdal
  • 4,815
  • 5
  • 32
  • 87
  • 1
    Also see https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – Marco13 Mar 12 '18 at 11:48

1 Answers1

4

there seems to be no such thing as "compile vs. does not compile" in the most general Class case.

This is not the case. Class and Class<?> follow the same restrictions as List and List<?>, or for any other generic type for that matter.

For example, both of these also compile just as well as your Class and Class<?> example.

List<?> integerList = new ArrayList<Integer>();
List<?> stringList = new ArrayList<String>();
Map<List, List> map = new HashMap<>();
map.put(integerList, stringList);

and

Map<List<?>, List<?>> map = new HashMap<>();
map.put(integerList, stringList);
Alanpatchi
  • 1,130
  • 9
  • 16
  • This does not compare `Class>` vs. `Class`. You're using the `List` type here. I'm asking about the case where `Class` or `Class>` is used in the code directly, not some other type. – Christian Neverdal Mar 12 '18 at 12:18
  • I just illustrated that whatever code that compiles or doesn't compile using `Class` and `Class>`, gives the exact type of compilation with `List` and `List>`, to point out that fact that the generic type `Class` doesn't have any special behavior from any other generic type. – Alanpatchi Mar 12 '18 at 12:23
  • I have edited my question. – Christian Neverdal Mar 12 '18 at 12:27