we have two process classes which are almost identical except One is used to process a float[] data and another is for a int[] data.
I am thinking to combine them into one. My original thinking is use generic for float[] and int[].
Java generic is new to me. So I wrote the following test method to see how generic works but I cannot make it working for me.
public <T> T caculate(T[] values)
{
T result;
for(int i = 0; i < values.length; i++)
{
result = result + values[i];
}
result = result/(values.length);
return result;
}
Anybody can modify above method for me? float and int is primitive type in Java. Probably above method is not right.
Unfortunately, you can’t do that with generics. Your best options is to bite the bullet and code the two classes separately; i.e. no generics.
In theory, you could try changing the arrays to
Integer[]andFloat[]and changing<T>to<T extends Number>. However:This liable to involve changing other parts of your code.
It is liable to make your processing code slower.
It will probably be difficult to express your processing algorithm in a generic way using
T extends Number. For a start, theNumberinterface doesn’t support arithmetic.I guess it would also be possible to solve this problem by wrapping the primitive arrays in some class that makes them look like arrays of (say) integers. But that is liable to give you problems with truncation, precision and so on … depending on the algorithms you are implementing. So this will only work in limited cases.