In C++ I can write a template function that takes the data type on which to act as an argument, so that a single function can be reused for more than on data type. Is there a provision for doing a similar thing in Java?
Thanks,
Roger
This person isn't asking about Generics. He's asking about template functions of the sort that are specified in <algorithm>
. The closest you could come in Java would be to define (genericized) Interfaces for each of the function types you want to be able to call and then roll your own utility library that accepted instances of the interfaces as input. For instance you could create the following interface
public interface UnaryOperator<T> {
public boolean test(T item);
}
and then create a utility class like so
public class Algorithms {
public static <T> void removeIf(Collection<T> c, UnaryOperator<T> op) {
Iterator<T> itr;
for (itr = c.iterator(); itr.hasNext(); ) {
T item = itr.next();
if (op.test(item)) {
itr.remove();
}
}
}
}
You can actually find this pattern in the Apache Commons Collections library, but its its not as flexible or extensive as the C++ algorithm's library. I think given any particular example of the STL functors and algorithms library you'd be able to compose something in Java that's similar, but there's no built in equivalent that I'm aware of. Most people I know (even C++ devs) consider <algorithm>
to be pretty arcane.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With