Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Very interesting question.</p> <p>The following code doesn't compile</p> <pre><code> Integer x = null; String s = null; if(x==s){} // error: incomparable types </code></pre> <p>JLS3#15.21.3 [1] says </p> <blockquote> <p>A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5)</p> </blockquote> <p>Apparently the previous example looks like an obvious programming error, so the spec tries to catch it and alert the programmer. There wouldn't have been any trouble is Java wanted to allow it. The workaround for the example is to cast one side to <code>Object</code>.</p> <p>Back to your question, we need to decide if <code>OtherEnum</code> can be cast to <code>T</code>, or the other way around. This is a surprisingly difficult question; following the procedure of JLS3#5.5 [2], the answer is no.</p> <p>It comes down to whether <code>OtherEnum</code> can be cast to <code>Enum&lt;T&gt;</code>; then we can find super types <code>X=Enum&lt;OtherEnum&gt;</code> and <code>Y=Enum&lt;T&gt;</code>, which are provably distinct parameterized types. So cast is illegal.</p> <p>Well, such specification is too elaborate, who in their right minds would care?</p> <p>You can work around it by casting one to <code>Object</code>, say <code>(Object)enumVal == OtherEnum.a</code></p> <p>Java 7 behaves differently, it does compile your code. I don't know the reason. It's possible that Java7 introduces a new bug. Or it has a new spec that allows the code (but we don't have access to the new spec). Another possibility is that I misunderstood the term "provably distinct parameterized types"; however without formal definition, it is intuitive that <code>Enum&lt;OtherEnum&gt;</code> and <code>Enum&lt;T&gt;</code> are distinct.</p> <p>ref</p> <p>[1] <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.3" rel="nofollow">http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.3</a></p> <p>[2] <a href="http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#20232" rel="nofollow">http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#20232</a></p>
    singulars
    1. This table or related slice is empty.
    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