Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); </code></pre> <p>When you use this version of the generic class Foo, then for the member variable <code>a</code>, the compiler is essentially taking this line:</p> <pre><code>private T[] a = (T[]) new Object[5]; </code></pre> <p>and replacing <code>T</code> with <code>Double</code> to get this:</p> <pre><code>private Double[] a = (Double[]) new Object[5]; </code></pre> <p>You cannot cast from Object to Double, hence the ClassCastException.</p> <p><strong>Update and Clarification:</strong> Actually, after running some test code, the ClassCastException is more subtle than this. For example, this main method will work fine without any exception:</p> <pre><code>public static void main(String[] args) { Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); System.out.println(f.getA()); } </code></pre> <p>The problem occurs when you attempt to assign <code>f.getA()</code> to a reference of type <code>Double[]</code>:</p> <pre><code>public static void main(String[] args) { Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); Double[] a2 = f.getA(); // throws ClassCastException System.out.println(a2); } </code></pre> <p>This is because the type-information about the member variable <code>a</code> is erased at runtime. Generics only provide type-safety at <em>compile-time</em> (I was somehow ignoring this in my initial post). So the problem is not </p> <pre><code>private T[] a = (T[]) new Object[5]; </code></pre> <p>because at run-time this code is really</p> <pre><code>private Object[] a = new Object[5]; </code></pre> <p>The problem occurs when the result of method <code>getA()</code>, which at runtime actually returns an <code>Object[]</code>, is assigned to a reference of type <code>Double[]</code> - this statement throws the ClassCastException because Object cannot be cast to Double.</p> <p><strong>Update 2</strong>: to answer your final question "why do arrays break this?" The answer is because the language specification does not support generic array creation. <a href="http://forums.sun.com/thread.jspa?threadID=530823" rel="noreferrer">See this forum post for more</a> - in order to be backwards compatible, nothing is known about the type of T at runtime.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload