0

I am studying Generics in java. I made a Map and initialized with 'new HashMap>()'. After that, I made an ArrayList to put into that variable. However, this code can not compile.

error message is:

"The method put(String, capture#1-of ? extends List) in the type Map> is not applicable for the arguments (String, List)"

on Map.put() method.

My code is below.

package org.owls.generic.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> tmpArr = new ArrayList<String>();
        tmpArr.add("A");
        tmpArr.add("B");
        List<?> value = new ArrayList<String>(tmpArr);
        Map<String, ? extends List<String>> testMap = new HashMap<String, List<String>>();
        testMap.put("K", value);
    }
};

I can not understand why compiler looks type, even I assigned inheritanced Class which is 'List'.

Sorry for my poor English and edit will be welcomed. Thanks for your answer:D

5
  • 1
    ? extends List<String> is not a supertype of List<?>. Commented Dec 13, 2013 at 2:23
  • Is there a reason you used wildcards? Are you experimenting with wildcards, or are you just trying to make it work? Commented Dec 13, 2013 at 2:40
  • @Bohemian It's just for Java study:) Commented Dec 13, 2013 at 7:32
  • @OliCharlesworth So how can I put some type of Collection into Map<String, ?>? After I saw your comment, I changed List<?> value to ArrayList<String> value but still can not put it into Map. Is there any ideas?:) Commented Dec 13, 2013 at 7:35
  • @JuneyoungOh: You cannot put any value except null into a Map<String, ?> Commented Dec 16, 2013 at 10:25

1 Answer 1

3

You cannot put anything except null into a generic type with the ? extends ... parameter. This is basic Generics -- since the type parameter is unknown, you cannot put anything into it because whatever you try to put is not guaranteed to be a subtype of that unknown type.

Recall the PECS (Producer extends, Consumer super) rule. ? extends can only be used for producers. Putting something in is a Consumer.

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

1 Comment

Thanks. Now I realize that I have tried something impossible:D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.