Java for-each loop says 'Incompatible Types' even though I am using generics

时间:2018-09-22 22:51:49

标签: java for-loop generics types each

I have a Node class that I am using for a directed graph in Java. The Node class is defined as so:

public class Node<E> {
    E val;

    public Node(E val) {
        this.val = val;
    }

    LinkedList<Node<E>> children = new LinkedList<>();
}

In the same package, I have a static method in main that utilizes the for-each loop on the children member variable of a Node object.

 static boolean processNode(LinkedList<Node> queue, HashSet<Node> visited, Node otherNode) {
        if (!queue.isEmpty()) {
            Node curr = queue.pop();

            if (curr.equals(otherNode) || visited.contains(curr)) {
                return true;
            }

            visited.add(curr);

            for (Node child: curr.children) {
                queue.add(child);
            }
        }

        return false;
    }

However, I get an error in the for-each loop:

Error:(62, 34) java: incompatible types: java.lang.Object cannot be converted to TreesAndGraphs.Node Information:java: /home/tam/IdeaProjects/AlgorithmsPractice/src/TreesAndGraphs/RouteExists.java uses unchecked or unsafe operations.

The children member variable is a LinkedList of Nodes, so why is it expecting Object when I iterate over it?

0 个答案:

没有答案