Java代码报错‘E cannot be resolved to a type’如何修复?
解决Java报错:'E cannot be resolved to a type'
报错原因是代码中使用了泛型参数E,但未在类或方法层面声明该泛型,导致编译器无法解析E的类型。以下是两种可行的修复方案:
方案一:为Driver类声明泛型参数E
将Driver类定义为泛型类,使整个类内的方法都能使用泛型E:
public class Driver<E> { public int[] computeDepths(AbstractTree<E> T, int n) { int[] depths = new int[n]; int i = 0; // 遍历树并计算每个位置的深度 for (Position<E> p : T.preorder()) { depths[i] = T.depth(p); i += 1; } return depths; } public static void main(String args[]) { } }
方案二:将computeDepths定义为泛型方法
如果不需要整个Driver类是泛型类,可单独给computeDepths方法声明泛型参数E:
public class Driver { public <E> int[] computeDepths(AbstractTree<E> T, int n) { int[] depths = new int[n]; int i = 0; // 遍历树并计算每个位置的深度 for (Position<E> p : T.preorder()) { depths[i] = T.depth(p); i += 1; } return depths; } public static void main(String args[]) { } }
两种方案都能让编译器正确识别泛型E,解决类型无法解析的问题。
内容的提问来源于stack exchange,提问作者esokumamon
相关产品推荐
相关产品推荐

