Using generic types in a static context
public static BTNode<E> treeCopy(BTNode<E> source)
{
if(source == null)
return null;
else
{
BTNode left = BTNode.treeCopy(source.left);
BTNode right = BTNode.treeCopy(source.right);
return new BTNode(source.data, left, right);
}
}
My questions is why can't I use the generic Type E in a static context? I tried search for several answers couldn't find an开发者_运维百科y that make snese.
You need to declare the generic type in the method signature. Since this is a static method - it cannot grab generic information from anywhere else. So it needs to be declared right here:
public static <E> BTNode<E> treeCopy(BTNode<E> source)
{
if(source == null)
return null;
else
{
BTNode<E> left = BTNode.treeCopy(source.left);
BTNode<E> right = BTNode.treeCopy(source.right);
return new BTNode(source.data, left, right);
}
}
E
can mean anything. To use E
(as a generic) you need to create an instance of an object. You cannot do this if you have a static method because the generic type-parameters are only in scope for an instance of the class (which includes its instance methods and instance fields).
Static members and fields belong to every instance of the class. So if you had an instance of BTNode<String>
and another instance of BTNode<Integer>
, what exactly should the static treeCopy
be using? String
or Integer
?
There is a workaroud; you have to tell the static method what E
means. So you will have to define it like this:
public static <E> BTNode<E> treeCopy(BTNode<E> source)
It would also help to take a second look at your design and see if this is actually what you want.
精彩评论