Note that there are some explanatory texts on larger screens.

plurals
  1. POConstrict generic class in Java
    text
    copied!<p>I have an operator class that has some classes and methods in it that deals with mathematical operations. The operator class is generic and extends Number so my operations can be with ints, doubles, floats, etc.</p> <pre><code>public class OperatorClass&lt;T extends Number&gt; </code></pre> <p>In this class there is an abstract class that provides a method in which numbers are operated upon using the calculate method</p> <pre><code>abstract class Op&lt;T extends Number&gt; { abstract T calculate(DataSet&lt;? extends Number&gt; ds); } </code></pre> <p>There are multiple classes that extend Op like the AddOp for example:</p> <pre><code>class AddOp&lt;T extends Number&gt; extends Op&lt;T&gt;{ public T calculate(DataSet&lt;? extends Number&gt; ds) { return ds.getLeft() + ds.getRight(); } } </code></pre> <p>And my DataSet is just a data class that looks like this:</p> <pre><code>public class DataSet&lt;T extends Number&gt; { private T left; private T right; public DataSet(T left, T right) { this.left = left; this.right = right; } public T getLeft() { return left; } public T getRight() { return right; } </code></pre> <p>}</p> <p>The problem I am having is that the line <code>ds.getLeft() + ds.getRight()</code> is not compiling because the Number abstract class cannot do a + operator. How do i get my DataSet to be a type of Number (like a wildcard class) so i can do math operations on it.</p> <p>Any help would be appreciated Thanks</p> <p><strong>Edit</strong></p> <p>So a workaround to the problem is that I used some if statements and then got the correct primitive datatype like so</p> <pre><code>Number result = null; if(ds.getLeft().getClass().equals(Integer.class)) result = new Integer(ds.getLeft().intValue() + ds.getRight().intValue()); .... return (T) result; </code></pre>
 

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