tags:

views:

353

answers:

5

Hi,

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

+2  A: 

In Java, parameterized types are called Generics. Sun has a good generics tutorial.

Asaph
A: 

Generic is your friend.

nanda
+1  A: 

No, Java has no functions, but you can create generic method. Look here

<T> void foo( T object )  {
/** there is your code */
}
Gaim
Java has no functions? Surely you meant something else. ;)
jalf
OK, show me some function. I know only methods, no functions because everything in Java has to be part of class. You can teach me, please.
Gaim
functions, methods ... potato, potato...
Asaph
+3  A: 
Generics are a facility of generic programming that was added to the Java
programming language in 2004 as part of J2SE 5.0. They allow "a type or method
to operate on objects of various types while providing compile-time type safety.

Souce wikipedia.

codaddict
+4  A: 

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.

Jherico