[英]cannot convert list to list error in java generics
Following is my simplified graph implementation 以下是我的简化图表实现
import java.util.ArrayList;
import java.util.List;
public class TreeNode<E extends Comparable<E>> {
private E data;
private List<TreeNode<E>> children;
public TreeNode(E value) {
data = value;
children = new ArrayList<>();
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public List<TreeNode<E>> getChildren() {
return children;
}
public void setChildren(List<TreeNode<E>> children) {
this.children = children;
}
}
And I am writing code to find if 2 nodes are connected in a directed graph. 我正在编写代码来查找有向图中是否连接了2个节点。 I am getting compilation error
我收到编译错误
public static boolean findIfPathExists(TreeNode<? extends Comparable<?>> start, TreeNode<? extends Comparable<?>> end) {
Set<TreeNode<? extends Comparable<?>>> visitedNodes = new HashSet<TreeNode<? extends Comparable<?>>>();
return findIfPathExists(start, end, visitedNodes);
}
private static boolean findIfPathExists(TreeNode<? extends Comparable<?>> start, TreeNode<? extends Comparable<?>> end,
Set<TreeNode<? extends Comparable<?>>> visitedNodes) {
if(start == end) return true;
visitedNodes.add(start);
List<TreeNode<? extends Comparable<?>>> children = start.getChildren();
for (TreeNode<? extends Comparable<?>> child : children) {
if(visitedNodes.contains(child)) continue;
if(findIfPathExists(child, end, visitedNodes)) return true;
}
return false;
}
I am getting error at line start.getchildren 我在行start.getchildren收到错误
Type mismatch: cannot convert from List<TreeNode<capture #11 -of? extends
Comparable<?>>> to List<TreeNode<? extends Comparable<?>>>
Add a type variable to your method signatures: 将类型变量添加到方法签名:
public static <T extends Comparable<T>> boolean findIfPathExists(
TreeNode<T> start, TreeNode<T> end) {
private static <T extends Comparable<T>> boolean findIfPathExists(
TreeNode<T> start, TreeNode<T> end, Set<TreeNode<T>> visitedNodes) {
and then use T
wherever you currently have ? extends Comparable<?>
然后在你现在的任何地方使用
T
? extends Comparable<?>
? extends Comparable<?>
. ? extends Comparable<?>
。
If you wanted to keep the wildcards, change the line from 如果您想保留通配符,请更改该行
List<TreeNode<? extends Comparable<?>>> children = start.getChildren()
to 至
List<? extends TreeNode<? extends Comparable<?>>> children = start.getChildren();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.