Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In general, Java generics are not appropriate for math.</p> <p>In Java:</p> <ul> <li>Generics are object only.</li> <li>There are no mathematical operators for objects.</li> </ul> <p>It looks like you can perform math on objects because you can do something like this:</p> <pre><code>Integer a = 1; Integer b = 2; Integer c = a + b; </code></pre> <p>But that is only due to autoboxing. What actually happens is the compiler replaces that code with this:</p> <pre><code>Integer a = new Integer(1); Integer b = new Integer(3); Integer c = Integer.valueOf(a.intValue() + b.intValue()); </code></pre> <p>With generics you can specify a bound so that your type must be Number or a subtype of it:</p> <pre><code>static &lt;N extends Number&gt; N multiply(N n1, N n2) { return n1 * n2; // but you cannot do this because the type is not known // so the compiler cannot do autoboxing } </code></pre> <p>If a supertype is known, you <em>can</em> call methods on them so you can do this as has been pointed out:</p> <pre><code>static &lt;N extends Number&gt; double multiply(N n1, N n2) { return n1.doubleValue() * n2.doubleValue(); } </code></pre> <p>But that is no different than the following:</p> <pre><code>static double multiply(double n1, double n2) { return n1 * n2; } </code></pre> <p>Except that the generic version can, for example, take BigDecimal as an argument which will of course not provide a reliable result (see <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#doubleValue%28%29" rel="nofollow">BigDecimal#doubleValue</a>). (Neither will Long for that matter.)</p> <p>If you were really determined you could program your own number classes and use polymorphism. Otherwise use overloads or (best of all) stick to one type.</p>
 

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