I’m learning generics in Java from C++ and am confused how to do math without operator overloading. Say I want to write a sumList class that’s just a list with a sum method.
public class sumList<T extends CanAdd<T>> {
private List<T> list;
public sumList() {
list = new List<T>();
}
public void addElement(T t) {
list.add(t);
}
public T getSum() {
T ans = null;
for (T t : list) {
if (ans == null) {
ans = t;
} else {
ans = ans.plus(t);
}
}
return ans;
}
}
and the interface I’m using is simply:
public interface CanAdd<T>
{
// returns a new T that's the sum of the object + other
public T plus(T other);
}
So this is simple enough when I create sumLists of classes I create, a Vector or a Point for example, because I can add the plus method defined by the interface. However, how would I change sumList so that I can also create sumList<Double> or sumList<Integer>?
Edits: Fixed minor mistakes.
As Kaleb said, if you only need this to work with Java Numbers then you should not worry about an interface and simply use T extends Number.
But if you really want to make this more generic and use your canAdd interface, then you need to write a wrapper class around the Number object and use that instead.
EDIT
Maybe you are looking at it the wrong way. Instead of having the classes that populate your list have a specific behaviour (in this case the sum), you should instead borrow some useful tricks from Functional programming.
You can write map, reduce and filter methods in Java. You have some boilerplate to get you to the point where you can use them but then you can easily create a reduce function for every type of object you want to sum and then apply that to your list.