Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To understand the strange behaviour, you need to pick apart what this does:</p> <pre><code>(o instanceof Number) ? ((Number) o).longValue() : DEFAULT_LONG </code></pre> <p>What we have here is a call to method that returns a <code>long</code>, and an instance of <code>Long</code>. Two <em>different</em> types. However the conditional operator <code>?</code> needs to produce a single type; either <code>long</code> or <code>Long</code>. And in order to do that, either the second operand must be boxed or the third operand must be unboxed.</p> <p>In this case, the JLS says that the third operand must be unboxed. <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25" rel="nofollow">JLS 15.25</a></p> <blockquote> <p><em>"If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T."</em></p> </blockquote> <p>And that means that your constants are being unboxed and then boxed again.</p> <p>Now boxing a primitive type is done by calling the boxed type's <code>valueof()</code> method. And these methods do slightly different things depending on the base type.</p> <ul> <li>For a floating point type, the <code>valueof</code> always creates a new object</li> <li>For an integral type, the <code>valueof</code> method sometimes creates a new object, and sometimes returns an existing object.</li> </ul> <p>And the latter is what is happening here. <code>Long.valueof(1L)</code> is always returning the same value, and the comparison with <code>==</code> is giving <code>true</code>.</p> <hr> <p>There are two "fixes" ... assuming you want to fix this:</p> <ul> <li>Replace the ternary operator with an <code>if</code> / <code>else</code> with a <code>return</code> in both branches.</li> <li><p>Cast the second operand to force it to be boxed:</p> <pre><code>return (o instanceof Number) ? (Long) ((Number) o).longValue() : DEFAULT_LONG; </code></pre></li> </ul>
    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.
    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