So I’m trying, for all intents and purposes, to realize for myself a java version of C++’s STL algorithm inner_product for vector parameters. So far, my code(which is probably fundamentally wrong) looks like this:
public static<T,K> double inner_product(Vector<T> v1, Vector<K> v2)
{
double isum = 0;
for(int i=0;i<v1.size()&&i<v2.size();i++)
{
isum+=v1.elementAt(i)*v2.elementAt(i);
}
return isum;
}
The problem is that the operator * is undefined for the types T, K. However my knowledge so far doesn’t cover predefining operators, though as far as I know it’s not possible in Java as well. Any help would be appreciated in the way of realizing the function to take generics. Thanks in advance.
There is no nice way to do this, for two reasons:
T,K) must refer to object types, not primitives.The closest you can get is something like this (modulo syntax errors, my generics are rusty):
This will work for the object wrappers around primitive types, i.e.
Doublebut notdouble, etc.Also, like your version, this returns
doubleno matter what type was passed in. And because of type erasure, this is pretty hard to fix.