Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wildcard instantiated List does not accept value

I don’t get why it’s not okay to put a String into the List below:

        List<? extends Comparable<String>> test = new ArrayList<String>();
        String string = "A";
        test.add(string); // why is this not ok? in fact "String" should be a subype of "? extends Comparable<String>

Can anyone please explain where the problem is? I know that there is no benefit in having a wildcard at this point because we can’t inherit from "String", but I want to understand what’s happening an why the compiler is complaining about it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Consider this:

class X implements Comparable<String> {
    @Override
    public int compareTo(String o) {
        return 0;
    }
}
List<? extends Comparable<String>> test = new ArrayList<X>();

Does it make sense to add a String to test?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading