如何使用构造函数将类型为 List<T> 的变量设置为类型为 ArrayList<T> 的值

How to set a variable with type List<T> to a value with type ArrayList<T> using the constructor

一个图节点的实现如下(我无法更改实现,因为它来自编码网站):

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

如果我将一个节点传递给下面的 copyGraph 函数,我将无法通过调用节点构造函数来制作该节点的副本,因为我得到

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
    }
}

我还能如何使用此实现创建新节点?

您可以使用 (ArrayList) node.neighbors

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

问题

API 设计不佳,仅供参考。构造函数应该接受 List 而不是 ArrayList。理想情况下,该代码为:

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

... 或者甚至更一般的 Collection 如果顺序不重要。

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

解决方法

解决糟糕设计的两种方法:转换或复制。

  • 如果您确定您的 List 对象实际上是一个 ArrayList,请按照正确的 .
  • 所示进行转换
  • 如果您不确定 List 对象的具体实现,请在传递 List.
  • 时构造一个新的 ArrayList
Node n = new Node ( node.val, new ArrayList < Node > ( nodesList ) );