I'm writing a function to sum two arrays (of not necessarily equal size) in Java and return the result.
Here's my attempt:
public static <T> T[] sumArrays(T[] lhs, T[] rhs) { T[] out = new T[Math.max(lhs.length, rhs.length)]; for (int i = 0; i < Math.max(lhs.length, rhs.length); ++i){ if (i < Math.min(lhs.length, rhs.length)){ out[i] = lhs[i] + rhs[i]; } else if (i < lhs.length){ out[i] = lhs[i]; } else /* if (i < rhs.length)*/{ out[i] = rhs[i]; } } return out; } But I have several observations notwithstanding the compile errors.
Why isn't this function in the Java library, which is gigantic in the extreme?
I was motivated to use generics, as you would use templates in C++.
I'm worried about getting deep copies of the input data;
lhsand ``rhs. Can anyone reassure me on this? C++ allows me to pass a constant reference; and I'll know for sure.Instantiation of
T[]out appears to be illegal with a generic type. What am I missing?Will the compiler optimise out my repeated
Math.max(lhs.length, rhs.length)?Compiler doesn't like
lhs[i] + rhs[i]. Presumably because it doesn't know the type of T, but C++ allows you do to this as it will not attempt to compile a template until it knows the type.Are going to take a deep copy of out when returning? Again, C++ compilers would not take an extra copy.
Perhaps I'm too old to get used to Java;-)
Tis unknown at runtime which is why you can't donew T[]