3

when I declare a Map or Map <Object,Object> I can put anything in this Map

Map map = new HashMap(); map.put(""); 

but if I declare it as Map <?,?> I can put nothing in it

Map<?,?> map = new HashMap(); map.put(""); 

it will goes wrong why ?

1

3 Answers 3

2
Map<?,?> map = new HashMap<Integer, Integer>(); // compiles just fine! 

? represents some fixed but unknown type. You can't put "" in a Map<Integer, Integer>, and a Map<?, ?> is allowed to be any type of Map, including a Map<Integer, Integer>.

Sign up to request clarification or add additional context in comments.

2 Comments

how can I use it , I declare a Map but I can`t put anything in it
@Wangbo you shouldn't use it for Maps you are going to put stuff into. You can use it for Maps you're going to take things out of, though.
1

In java collection Frame, ? means unknown type. You can only read elements from that, but can not add elements except for NULL value.

So you can compile fine like below:

 Map<?,?> map = new HashMap(); map.put(null, null); 

Comments

0

For this snippet code:

 Map<?,?> map = new HashMap(); 

Map<?,?> means a Map typed to an unknown type.
The question mark (?), called the wildcard,the wildcard means "the value type parameter could be anything", it doesn't mean "you can use this as if it were anything you want it to be".
For more info go to link

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.