ArrayList构造函数在使用nCopes(int, generic)时未定义。

huangapple go评论74阅读模式
英文:

ArrayList constructor undefined when using nCopes(int, generic)

问题

我有以下的类:

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
英文:

I have the following class:

class Node&lt;T extends Comparable&lt;T&gt;&gt; {

and this is the constructor am using:

	Node(T data, int h) {
		this.tower = new ArrayList&lt;Node&lt;T&gt;&gt;(Collections.nCopies(h, data));
		this.data = data;
	}

Why is it giving me the following error:

The constructor ArrayList&lt;Node&lt;T&gt;&gt;(Collections.nCopies(h, data)) is undefined

答案1

得分: 2

你正在构建一个用于包含 Node<T>ArrayList,但你却在构造函数中提供了一个 List<T>(而不是 List<Node<T>>)。你可能想要这样做:

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

You are building an ArrayList that is meant to contain Node&lt;T&gt; but you are supplying to the constructor a List&lt;T&gt; (and not List&lt;Node&lt;T&gt;&gt;), you probably want

Node(T data, int h) {
    this.tower = new ArrayList&lt;Node&lt;T&gt;&gt;(Collections.nCopies(h, new Node&lt;T&gt;(data)));
    this.data = data;
}

答案2

得分: 0

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

Node(T data, int h) {
    this.tower =
        IntStream.range(0, h)              // 这两行代码执行的是
                 .mapToObj((ignore) -> data) // Collections.nCopies 的操作

                 .map(Node::new) // 但是在这里,我们创建了独立的对象
                 .collect(Collectors.toList());
    this.data = data;
}

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

英文:

Collections.nCopies is probably not what you want, as it will not actually create copies of the object itself, but only of the reference to it. Which means, changing the value of one of these nodes changes all, which is likely not what you want. If it isn't, then here's your solution:

Node(T data, int h) {
    this.tower =
        IntStream.range(0, h)              // these two lines do
                 .mapToObj((ignore)-&gt;data) // what Collections.nCopies does

                 .map(Node::new) // but here we&#39;re creating unique objects
                 .collect(Collectors.toList());
    this.data = data;
}

This way, each node is a separate object, but they all have the same initial value.

huangapple
  • 本文由 发表于 2020年7月25日 07:19:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63082620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定