Diamond and Generic Methods

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu May 5 08:18:19 PDT 2011


On 05/05/11 16:06, Jesper Öqvist wrote:
> So, after searching the archives and scouring the JSR334 v0.875 draft, I
> have a question about Diamond. While the specification draft does not
> explicitly disallow it, it seems weird that this works (Java7 developer
> preview b139):
>
> class C {
> <T>  void identity(T a) { return a; }
>     void m() {
>       identity(new java.util.ArrayList<>());
>     }
> }
>
> Since there is a distinction between raw types and parameterized types
> with inferred type arguments (in the discussion part of the Diamond
> section in JSR334), it would be interesting to know what type is
> instantiated in the above example.
Hi
The above code is equivalent to the following:

class C {
static<Z>  ArrayList<Z>  makeArrayList() { return new ArrayList<Z>(); }

<T>  void identity(T a) { return a; }
    void m() {
      identity(makeArrayList());
    }
}

In both cases, an ArrayList<Object> is created - note that, because of 
the restrictions in Java method type-inference, the information on 
formal argument type is not used to infer a better type. In this 
particular case it might not seem a big problem, but in the following 
case you  get a compile-time error:

class C {
static<Z>  ArrayList<Z>  makeArrayList() { return new ArrayList<Z>(); }

<T>  T identity(T a) { return a; }
    void m() {
      //error - ArrayList<Object>  found - expected ArrayList<String>
      ArrayList<String>  s = identity(makeArrayList());
    }
}


Maurizio

> /Jesper
>




More information about the coin-dev mailing list