Using Java:
I didn’t want to waste peoples time and post this here, but my googling-skills have failed me and I can’t find the answer. I was looking through some supplied code and they used
public static <E> void printTree(TwoFourTree<E> tf)
(For reference we are converting from a Red-Black tree to a Two-Four Tree). When I first approached this problem I would use instead of and not even include in the initial method declaration of public static void. However I ran into issues, and throwing in this <E> solved all my problems, despite using <Integer> instead of <E> everywhere else.
So my question is, can someone please explain to me what exactly the <E> does in
public static <E> void
This is a Java feature known as Generics.
Why would you want to use Generics? Well, the following gives one scenario where they are useful. Back in the “bad old days”, if you wanted to have a class that could work with any objects you had to declare all it’s interfaces in terms of objects, e.g.
However, this sucks, because you get no type-safety – you could write code like the following:
Generics fixes this, by allowing you to strongly-type your class, but in a generic manner. For example: