How can I replace those 2 functions with one using something like C++ tempates?
public void verify(final int[] array, final int v) {
for ( final int e : array ) if ( e == v || v == e ) return;
abort_operation();
}
public void verify(final double[] array, final double v) {
for ( final double e : array ) if ( e == v || v == e ) return;
abort_operation();
}
You can't, basically. Java generics don't work with primitive types. You could do it with reflection, but it would be ugly. You could also do it with the boxed types, like this:
public <T> void verify(T[] array, T value) {
if (!Arrays.asList(array).contains(value)) {
abortOperation();
}
}
... but that would only work for Integer[]
and Double[]
, not int[]
and double[]
.
That's why the Arrays
class has so many overloads for methods like binarySearch
... if your method could have been made generic, so could those ones.
Fundamentally, generics are not the same as C++ templates. They cover a lot of the same use cases, but they're not the same, and you shouldn't be surprised to see some areas covered by one but not the other.
See more on this question at Stackoverflow