[ACCEPTED]-Using generic types in a static context-static

Accepted answer
Score: 26

You need to declare the generic type in 4 the method signature. Since this is a static 3 method - it cannot grab generic information 2 from anywhere else. So it needs to be declared 1 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);
     }
}
Score: 13

E can mean anything. To use E (as a generic) you 15 need to create an instance of an object. You 14 cannot do this if you have a static method 13 because the generic type-parameters are 12 only in scope for an instance of the class 11 (which includes its instance methods and 10 instance fields).

Static members and fields 9 belong to every instance of the class. So 8 if you had an instance of BTNode<String> and another instance 7 of BTNode<Integer>, what exactly should the static treeCopy be 6 using? String or Integer?

There is a workaroud; you have 5 to tell the static method what E means. So 4 you will have to define it like this:

public static <E> BTNode<E> treeCopy(BTNode<E> source)

It 3 would also help to take a second look at 2 your design and see if this is actually 1 what you want.

More Related questions