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);
}
}
我的问题是为什么我不能在静态上下文中使用通用类型 E?我尝试搜索了几个答案,但找不到任何使 snese 的答案。
最佳答案
您需要在方法签名中声明泛型类型。由于这是一种静态方法 - 它无法从其他任何地方获取通用信息。所以需要在这里声明:
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);
}
}
关于java - 在静态上下文中使用泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4209080/