Shevek (shevek) wrote,
Shevek
shevek



I can kind of see what they were getting at (explanation not included here, but something to do with not inheriting the full details of element types into the parent type, and not sure that I agree). But take a look at the following:


import java.util.*;

public class Generics {
    class B { }
    class C extends B { }
    class D extends B { }
    class S<T> { }

    List<? extends B>     list0 = new ArrayList<C>();
    {
        /* Cannot add to list parameterised with ?.
         * list0.add(new D());
         */
    }

    /* Cannot construct using subclass!
     * List<S<? extends B>> list1 = new ArrayList<S<C>>();
     */

    Map<String,S<? extends B>>  map0 =
                    new HashMap<String,S<? extends B>>();
    {
        /* Can mix types here. */
        map0.put("C", new S<C>());
        map0.put("D", new S<D>());
    }

    Map<String,? extends B>   map1 = new HashMap<String,C>();
    /* Cannot construct using subclass either.
     * Map<String,S<? extends B>>   map2 = new HashMap<String,S<C>>();
     */
}




Of additional note is the question in Stroustrup's FAQ as to why you cannot pass a vector as a vector - it prevents you adding an Orange to the list in the function. C++ does it by requiring strict typing and permitting writing. Java does it by passing List and preventing you from writing to the list.

It does annoy me that none of these restrictions are a direct consequence of erasure. They've actually messed it up.

Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments