I currently have an interface Ring that specifies methods like add, multiply, and so on. Thus, I can make a class of vectors whose elements are of type E that has an addition method, a dot product, etc. as long as E extends Ring. For example, a very simple class might look like
public class Vector<E extends Ring<E>> {
List<E> data;
public Vector() {
// constructor implementation here
}
public E dot(Vector<E> other) {
// initialize ``result" somehow
for (int index=0; index<data.size(); index++) {
result.add(data.get(index).multiply(other.get(index)));
}
return result;
}
}
In this simple example, one could simply initialize the result as data.get(0).multiply(other.get(0)) and then start the for loop at 1, but I'd like to know if there is a way to specify that there is a ``zero element" of type E.
Ideally, I'd like to specify that E has a static method called zero() so that the zero element is just E.zero(). I can't seem to figure out a way to do this. On the other hand, I can't just add a zero() method to the Ring interface because then I would have to do something like (new E()).zero(), and of course a generic constructor cannot be made in that way. There is a silly shortcut involving something like E zero = data.get(0).zero(), but this does not seem very nice and only works if I already have another instance of an element of type E floating around (which may not be the case in another context). So, is there any nice way to specify the existence of such a zero element that is guaranteed to be implemented in any class E that extends Ring?