【问题标题】:ArrayList constructor undefined when using nCopes(int, generic)使用 nCopes(int, generic) 时未定义 ArrayList 构造函数
【发布时间】:2020-07-24 23:19:00
【问题描述】:

我有以下课程:

class Node<T extends Comparable<T>> {

这是正在使用的构造函数:

    Node(T data, int h) {
        this.tower = new ArrayList<Node<T>>(Collections.nCopies(h, data));
        this.data = data;
    }

为什么会出现以下错误:

The constructor ArrayList<Node<T>>(Collections.nCopies(h, data)) is undefined

【问题讨论】:

    标签: java generics arraylist


    【解决方案1】:

    您正在构建一个包含 Node&lt;T&gt;ArrayList,但您正在向构造函数提供 List&lt;T&gt;(而不是 List&lt;Node&lt;T&gt;&gt;),您可能想要

    Node(T data, int h) {
        this.tower = new ArrayList<Node<T>>(Collections.nCopies(h, new Node<T>(data)));
        this.data = data;
    }
    

    【讨论】:

    • @vzdiegocm 不客气,请随时将其标记为假定答案
    【解决方案2】:

    Collections.nCopies 可能不是您想要的,因为它实际上不会创建对象本身的副本,而只会创建对它的引用。这意味着,更改这些节点之一的值会改变一切,这可能不是您想要的。如果不是,那么这是您的解决方案:

    Node(T data, int h) {
        this.tower =
            IntStream.range(0, h)              // these two lines do
                     .mapToObj((ignore)->data) // what Collections.nCopies does
    
                     .map(Node::new) // but here we're creating unique objects
                     .collect(Collectors.toList());
        this.data = data;
    }
    

    这样,每个节点都是一个单独的对象,但它们都具有相同的初始值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多