hi, I tried most of this.  I see two lines with the same code, but one is marked
ok, the other throws ClassCastException?

  n = tokens.get(0); // ok
  n = tokens.get(0); // throws ClassCastException

When I ran this (in Java 8), it ran OK.

Any idea why your try behaved differently?

I did see that 
  n = generalize.get(0); // gives a compile error
which can be overcome with a cast, but that seems like a bad burden to put on 
users,
compared to not having the wildcard in the returned result.
  

-Marshall

On 8/2/2019 3:00 PM, Hai-son X Nguyen wrote:
> Thanks for the reference Marshall,
>
> Try this code:
> public static void main(String[] args) {
>
>    List<Number> tokens = new ArrayList<>();
>    tokens.add(3);
>    tokens.set(0, 4);
>
>    ArrayList<? super Number> generalize = (ArrayList<? super Number>) tokens; 
> // Upcasts all to number
>    Number n = 5;
>    generalize.set(0, n);              // ok
>    var x = generalize.get(0);         // ok
>    // n = generalize.get(0);          // compile error
>    System.out.println(tokens.get(0)); // ok prints 5
>    x = tokens.get(0);                 // ok
>    n = tokens.get(0);                 // ok
>
>    List unknown = tokens;             // warning
>    unknown.set(0, "foo");             // warning
>
>    // String t = tokens.get(0);          // compile error
>    // String t = (String) tokens.get(0); // compile error
>    System.out.println(tokens.get(0));    // ok prints "foo"
>    n = tokens.get(0);                    // throws ClassCastException
>
> }
>
>> In fact, there's no cast I could figure out to make "generalize.set" work at
>> all, except by changing its definition to use ArrayList (bare with no generic
>> argument):
>>
>>     ArrayList generalize = (ArrayList<? extends Number>) tokens; //compiles 
>> with
>> warnings,
>>     generalize.set(0, 7);  // works at runtime
> I thought we can do a upcast and use <? super FeatureStructure> which gets 
> around the set problem you found but it looks like there are problems on the 
> get side...
> The use of var is possible to get around the immediate errors but that is 
> Java 10+
>
> Moved the example to get the runtime error at the end
>
> The run time exception comes in the get() call and setting it to the generic 
> type. (
>
> Hai-Son
>
> NOTICE TO RECIPIENT:  If you are not the intended recipient of this e-mail, 
> you are prohibited from sharing, copying, or otherwise using or disclosing 
> its contents.  If you have received this e-mail in error, please notify the 
> sender immediately by reply e-mail and permanently delete this e-mail and any 
> attachments without reading, forwarding or saving them.  Thank you.

Reply via email to