Studying Java, I’ve come across generic methods.
public <T> void foo(T variable) { }
That is, a method which takes a parameter with an undecided type (á la PHP?). I’m however unable to see how this would be a good solution – especially since I’ve come to fall in love with a strongly typed languages after coming from a loose ones.
Is there any reason to use generic methods? If so, when?
Generics, among other things, give you a way to provide a template — i.e. you want to do the same thing, and the only difference is the type.
For example, look at the List API, you will see the methods
add(E e)For every list of the same type you declare, the only thing different about the
addmethod is the type of the thing going into the list. This is a prime example of where generics are useful. (Before generics were introduced to Java, you would declare a list, and you could add anything to the list, but you would have to cast the object when you retrieved it)More specifically, you might want 2 ArrayList instances, one that takes type1 and one that takes type2. The list code for
addis going to do the same thing, execute the same code, for each list (since the two lists are bothArrayListinstances), right? So the only thing different is what’s in the lists.(As @michael points out,
addisn’t a true example of a generic method, but there are true generic methods in the API linked, and the concept is the same)