Home > front end >  How to set a variable with type List<T> to a value with type ArrayList<T> using the cons
How to set a variable with type List<T> to a value with type ArrayList<T> using the cons

Time:11-16

An implementation of a graph node is as follows (I cannot change the implementation as it is from a coding website):

class Node {
    public int val;
    public List<Node> neighbors;
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

If I pass a node to my copyGraph function below, I wouldn't be able to make a copy of that node by calling the Node constructor because I get

incompatible types: List cannot be converted to ArrayList

class Solution {
    public Node copyGraph(Node node) {
        Node n = new Node(node.val, node.neighbors);
        //do some code
    }
}

How else could I make a new Node with this implementation?

CodePudding user response:

That API is poorly designed, FYI. The constructor should accept a List rather than ArrayList. Ideally that code would be:

public Node ( int _val , List < Node > _neighbors ) { … }

… or perhaps even the more general Collection if order were unimportant.

public Node ( int _val , Collection < Node > _neighbors ) { … }

As a workaround:

  • If you know for sure that your List object is actually an ArrayList, cast as shown in the correct Answer by coconan.
  • If you are not sure of the concrete implementation of your List object, construct a new ArrayList while passing your List.
Node n = new Node ( node.val, new ArrayList < Node > ( nodesList ) );

CodePudding user response:

You can cast node.neighbors to ArrayList with (ArrayList<Node>) node.neighbors

class Solution {
    public Node copyGraph(Node node) {
        Node n = new Node(node.val, (ArrayList<Node>) node.neighbors);
        //do some code
    }
}
  • Related