Failed to convert list to list in Java generics. Error
•
Java
Here is my simplified diagram 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; } }
I'm writing code to find out if two nodes are connected in a directed graph I received a 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,visitedNodes)) return true; } return false; }
I'm good at start Getchildren received an error
Type mismatch: cannot convert from List<TreeNode<capture #11 -of? extends Comparable<?>>> to List<TreeNode<? extends Comparable<?>>>
Solution
Add a type variable to the method signature:
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) {
Then use t anywhere you are now? Expand comparable
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码