Java generics, add all int / vectors to the list

I am learning generics in Java from C ++ and am confused how to do math without operator overloading. Let's say I want to write a class sumList

that is 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 just:

public interface CanAdd<T>
{
    // returns a new T that the sum of the object + other
    public T plus(T other);
}

      

So it's easy enough when I create sumList

classes that I create, for example, Vector

or Point

because I can add a plus method defined by the interface. However, how do I change sumList

so that I can create sumList<Double>

or sumList<Integer>

?

Editing: Minor bugs fixed.

+3


source to share


2 answers


As Caleb said, if you only need this to work with Java numbers, you don't have to worry about the interface and just use T extends Number.

But if you really want to make it more general and use your canAdd interface, then you need to write a wrapper class around the Number object and use that instead.

EDIT



You may be looking at this the wrong way. Instead of the classes that populate your list have specific behavior (in this case, the sum), you should instead take some useful tricks from functional programming.

You can write methods for displaying, reducing, and filtering in Java. You have some pattern to get you to the point where you can use them, but then you can easily create a reduction function for each type of object you want to sum and then apply it to your list.

+3


source


Why not just use the base class Double and Integer, Number?

public class sumList<T extends Number>

Thus, there is no need to implement the canAdd interface or create wrappers to use paired and integers with this interface.



Edit: but if you really need to make this work for custom classes, I think you need to create a wrapper class that will provide the required appAdd interface.

Or use a language like Scala or Groovy that gives you access to mixins!

0


source







All Articles