7
以下是我的簡化圖實現不能轉換列表,列表錯誤在Java泛型
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;
}
}
而且我寫的代碼找到,如果2個節點連接有向圖。我得到的編譯錯誤的行
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;
}
我收到錯誤start.getchildren
Type mismatch: cannot convert from List<TreeNode<capture #11 -of? extends
Comparable<?>>> to List<TreeNode<? extends Comparable<?>>>
的問題改線 是通配符可以是任何東西,因此編譯器將不允許寫操作,如'visitedNodes.add(start);'(我猜是你得到錯誤的那一行 - 提示:不要讓我們猜測)。 – Thomas
@Thomas大概是包含'List >>'。 –