Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Reason is that you are declaring variable <code>a</code> to be a raw list i.e. <code>List</code> without any associated type:</p> <pre><code>List a = new ArrayList&lt;String&gt;(); </code></pre> <p>For that matter even this will compile &amp; run:</p> <pre><code>List a = new ArrayList&lt;Date&gt;(); a.add(new Integer(5)); </code></pre> <p><strong>Also a note about <code>generics</code> and <code>type erasure</code> here:</strong></p> <p>Generics are implemented by Java compiler as a front-end conversion called erasure. Type erasure applies to the use of generics. When generics are used, they're converted into compile time checks and run time type casts. </p> <p>Due to type erasure mechanism this code:</p> <pre><code>List&lt;String&gt; a = new ArrayList&lt;String&gt;(); a.add("foo"); String x = a.get(0); </code></pre> <p>gets compiled into:</p> <pre><code>List a = new ArrayList(); a.add("foo"); String x = (String) a.get(0); </code></pre> <hr> <p>Similarly your code:</p> <pre><code>List a = new ArrayList&lt;String&gt;(); a.add(new Integer(5)); </code></pre> <p>gets compiled into this (<strong>due to type erasure</strong>):</p> <pre><code>List a = new ArrayList(); a.add(new Integer(5)); </code></pre> <p>Thus no compilation or run time error is generated.</p> <p><strong>However you will note the difference when you try to do get item from the list:</strong></p> <pre><code>int i = a.get(0); // compilation error due to type mismatch </code></pre> <p>Which is due to the fact that your list is declared as raw type. To avoid this error you need to either use generics to declare your list OR else do a type cast like above. i.e.</p> <p>Either use generic type in your list:</p> <pre><code>List&lt;Integer&gt; a = new ArrayList&lt;Integer&gt;(); a.add(new Integer(5)); int i = a.get(0); </code></pre> <p>Or else do this casting: (<strong>not recommended</strong>)</p> <pre><code>List a=new ArrayList&lt;Date&gt;(); a.add(new Integer(5)); int i = (Integer) a.get(0); </code></pre> <p><strong>PS:</strong> Note that at run time there's no way of finding out that particular type e.g. String was used for declaring your list object.</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.
    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