Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your second example does not result in a compiler warning in my eclipse, nor can I think of a reason why it should. It is therefore my preferred solution.</p> <p>The reason unchecked warnings exist is that ignoring them can cause <em>heap pollution</em>:</p> <p>Ordinary casts are checked, i.e. they result in a <code>ClassCastException</code> if the value is not compatible with the desired type. Unchecked casts do not guarantee that, i.e. they can succeed even if the value is not of the proper type. This can result in a variable holding a value that is not a subtype of its declared type, a condition the Java spec <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.2" rel="nofollow">calls</a> "heap pollution". To ensure integrity of the runtime type system, the Java compiler will insert ordinary casts whenever a variable of generic type is used. In the presence of heap pollution, these casts can fail.</p> <p>For instance, the program:</p> <pre><code>static void appendTo(List list) { list.add(1); // unchecked warning } static void printLengths(List&lt;String&gt; strings) { for (String s : strings) { // throws ClassCastException System.out.println(s.length()); } } public static void main(String[] args) throws Exception { List&lt;String&gt; strings = new ArrayList&lt;&gt;(); strings.add("hello"); appendTo(strings); printLengths(strings); } </code></pre> <p>throws a <code>ClassCastException</code> at a line that does not contain a cast in the source code. This is likely to severely confuse most programmers.</p> <p>That is why I recommend to use checked casts whenever possible, either with a non-generic cast, or (in generic code) a reflective cast:</p> <pre><code>class Habitat&lt;T&gt; { private final Class&lt;T&gt; clazz; private List&lt;T&gt; inhabitants; void add(Object o) { inhabitants.add(clazz.cast(o)); } } </code></pre>
    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. 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.
 

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