Java regarding <E> in public static <E> void
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, eg
public class MySuperList
{
public void Add(object a) { }
}
However, this sucks, because you get no type-safety - you could write code like the following:
// Your code
MySuperList list = new MySuperList();
cars.Add(new Car("Ford Mondeo"));// Works
cars.Add(new Fish("Herring")); // Works - which is a shame as a Fish is not a car!
Generics fixes this, by allowing you to strongly-type your class, but in a generic manner. For example:
public class MySuperList<T>
{
// Add method will only accept instances of type T.
public void Add(T a) { }
}
// Your code
MySuperList<Cars> list = new MySuperList<Cars>();
cars.Add(new Car("Ford Mondeo"));// Works
cars.Add(new Fish("Herring")); // Compile-time error.
Instead of writing
public static Integer ...
public static Double ...
public static Long ...
...
all you do is create generics method
public static <E>
It creates a generic method; ie it allows you to use a TwoFourTree
that holds any type of object as your argument (in this case).
If you, for example, wanted to only accept TwoFourTree
s that held objects of type List
, you would define the method as
public static <E extends List> void ...
If you wanted only Number
objects ( Integer
, Double
etc.) you would do
public static <E extends Number> void ...
This is a reason why creating such methods can in fact be useful. I should point out that the fun doesn't end there, you can do the same using multiple type parameters, for instance:
public static <T, S extends Number> void ...
I think you might find it beneficial to read this tutorial on generic methods if you'd like to learn more.
链接地址: http://www.djcxy.com/p/11382.html上一篇: 具有分析功能的NoSQL