What does Map<?, ?> mean in Java?

2020-02-14 02:33发布

问题:

What does Map<?, ?> mean in Java?
I've looked online but can't seem to find any articles on it.

edit : I found this on MP3 Duration Java

回答1:

? indicates a placeholder in whose value you are not interested in (a wildcard):

HashMap<?, ?> foo = new HashMap<Integer, String>();

And since ? is a wildcard, you can skip it and still get the same result:

HashMap foo = new HashMap<Integer, String>();

But they can be used to specify or subset the generics to be used. In this example, the first generic must implement the Serializable interface.

// would fail because HttpServletRequest does not implement Serializable
HashMap<? extends Serializable, ?> foo = new HashMap<HttpServletRequest, String>(); 

But it's always better to use concrete classes instead of these wildcards. You should only use ? if you know what your are doing :)



回答2:

Map<?,?> means that at compile time, you do not know what the class type of the key and value object of the Map is going to be.

Its a wildcard type. http://download.oracle.com/javase/tutorial/extra/generics/wildcards.html



回答3:

Since Java5, Generics are provided with the language. http://download.oracle.com/javase/tutorial/java/generics/index.html

The notation means that the Map you are creating, will accept an object of class A as a key and an object of class B as a value.

This helps you as a developer so you wont cast anymore an Object to the correct class. So you wont be able to use the map with keys other than A and objets other than B. Avoiding ugly casts and providing compile time constraints



回答4:

Map<?,?> tells you that you can use every object for key and value in your map.

But usually it is more useful to use generics like that:

Map<String, YourCustomObject> map

So in this map, you can only put a String as key and YourCustomObject as value.

See this tutorial on generics.



回答5:

The ? is the wildcard in generics. Sun...er...Oracle has a nice tutorial on generics here. There's a separate section on wildcards.

You'd probably get a better answer if you posted more context to your question, such as where you saw Map<?, ?>.