加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

无法在java泛型中将列表转换为列表错误

发布时间:2020-12-15 00:45:12 所属栏目:Java 来源:网络整理
导读:以下是我的简化图表实现 import java.util.ArrayList;import java.util.List;public class TreeNodeE extends ComparableE { private E data; private ListTreeNodeE children; public TreeNode(E value) { data = value; children = new ArrayList(); } pub
以下是我的简化图表实现
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,visitedNodes)) return true;
    }
    return false;
}

我在行start.getchildren收到错误

Type mismatch: cannot convert from List<TreeNode<capture #11 -of? extends 
Comparable<?>>> to List<TreeNode<? extends Comparable<?>>>

解决方法

在方法签名中添加一个类型变量:
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) {

然后在你现在的任何地方使用T?扩展Comparable<?>.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读