Is casting from Wildcard to a specific generic parameterized type an example of capture conversion in Java?

329 Views Asked by At

For the following code that compiles without error and runs without exception:

public class Main
{
    public static void main(String[] args) {
        List<?> unbounded = new ArrayList<String>();

        List<String> strList = (List<String>) unbounded;    // Is this a capture conversion?
        List<Integer> intList = (List<Integer>) unbounded;  // Is this a capture conversion?
    }
}

Is the above code snippet an example of Capture Conversion working in Java?

According to JLS,

There exists a capture conversion from a parameterized type G<T1,...,Tn> (§4.5) to a parameterized type G<S1,...,Sn>, where, for 1 ≤ i ≤ n :

  • If Ti is a wildcard type argument (§4.5.1) of the form ?, then Si is a fresh type variable whose upper bound is Ui[A1:=S1,...,An:=Sn] and whose lower bound is the null type (§4.1).

I comprehend the above statement as follows: If the wildcard is of the form '?', there exists a capture conversion from G<T> to G<S> as long as 'S' is within the bound of Object(upper bound) and null(lower bound).

So, for example in the above code snippet, converting 'List<?>' to 'List<Integer>' will be a capture conversion, which would not throw any runtime exception (which is also stated in JLS)? Is that correct? Also, is it correct to say that it doesn't throw runtime exception due to type erasure?

If that's the case, wouldn't capture conversion undermine type safety? According to JLS, capture conversion is introduced to make wildcards more useful without undermining the type system?

0

There are 0 best solutions below