0

I do not understand why the below code works:

class MyMap<T> {
    T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}

public class GenTest {
    public static void main(String args[]) {
        MyMap<String> map = new MyMap<String>();   // *
        map.set("dog");
        System.out.println(map.get());
    }
}

But, if I change the marked * row to this:

MyMap<? extends String> map = new MyMap<String>();

then it does not compile.

It works also if I have this:

MyMap<? super String> map = new MyMap<String>();

Could You please help me? Thank you in advance!

MuellerDavid
  • 67
  • 1
  • 7
  • I do not think that it would be duplicated. I have already read the answer but it does not go about a list but a normal class. I do not understand how the Java Compiler detect that I want to change some value... – MuellerDavid May 04 '15 at 15:08
  • 1
    It is a duplicate. Generics apply for collections and non collections. The fact it uses collections to demonstrate the usage doesn't mean it's limited to it. Also, there are more than 1 answer that cover this. Check, for example, the second most voted answer, where it doesn't uses collections at all to explain this. – Luiggi Mendoza May 04 '15 at 15:12
  • Hi Luiggi, thank you. You can drop my question. Best Regards, David – MuellerDavid May 04 '15 at 15:33

0 Answers0