Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is the way generics work in Java. Class String implements interface CharSequence, but you can't cast List&lt;CharSequence&gt; to List&lt;String&gt; (or vice versa). But you can cast ArrayList&lt;String&gt; to List&lt;String&gt; (and List&lt;String&gt; to ArrayList&lt;String&gt; - at least compiler won't complain, but you'll get a runtime exception if your List object isn't an instance of ArrayList).</p> <p>What if it were possible? Here's an example:</p> <pre><code>1. List&lt;String&gt; listOfStrings = new ArrayList&lt;String&gt;(); // piece of cake! 2. List&lt;Object&gt; listOfObjects = (List&lt;Object&gt;) listOfString; // String is a subclass ofObject, so why not? 3. listOfObjects.add(new Object()); // obviously correct 4. String s = listOfString.get(0); // ouch! We've just put an Object into this list, but generic type promises there are only Strings! </code></pre> <p>This is why there's a compilation error in line 2. Of course, you can fool the compiler and try this:</p> <pre><code>A&lt;I&gt; myobj = null; A genericA = new B(); myobj = (A&lt;I&gt;) genericA; </code></pre> <p>This will work because generic types are removed in the runtime. You can do this also with lists:</p> <pre><code>List&lt;String&gt; listOfStrings = new ArrayList&lt;String&gt;(); List genericList = listOfStrings; genericList.add(new Object()); String s = listOfStrings.get(0); </code></pre> <p>This code will compile (with warnings), but you will get an exception in the runtime:</p> <pre><code>Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String </code></pre> <p>This code:</p> <pre><code>myobj = (A&lt;I&gt;) Class.forName("B").newInstance(); </code></pre> <p>works, because method <em>newInstance()</em> returns an instance of java.lang.Object. Compiler has no idea what it will return in the runtime, so it allows casting it to everything. Because of the <a href="http://docs.oracle.com/javase/tutorial/java/generics/erasure.html">Type Erasure</a>, in the runtime A&lt;I&gt; is just A, and since B is a subclass of A, you can cast an instance of B to A.</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