I am writing a function to sum two arrays (not necessarily the same size) in Java and return the result.
Here is 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 { out[i] = rhs[i]; } } return out; }
But I have a few observations, despite compilation errors.
Why doesn't this feature exist in the Java library, which is extremely extreme?
I was motivated to use generics, since you would use templates in C ++.
I am worried about getting deep copies of the input; lhs and `` rhs. Can anyone reassure me about this? C ++ allows me to pass a permalink; and I know for sure.
Activating T[] out seems illegal with a generic type. What am I missing?
Will the compiler optimize my repeated Math.max(lhs.length, rhs.length) ?
The compiler does not like lhs[i] + rhs[i] . Presumably because he does not know the type of T, but C ++ allows this, since he will not try to compile the template until he knows the type.
6) Are you going to get a deep copy when you return? Again, C ++ compilers do not take an extra copy.
I may be too old to get used to Java; -)
java
Bathsheba
source share