英文:
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<T extends Comparable<T>> {
and this is the constructor am using:
Node(T data, int h) {
this.tower = new ArrayList<Node<T>>(Collections.nCopies(h, data));
this.data = data;
}
Why is it giving me the following error:
The constructor ArrayList<Node<T>>(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<T>
but you are supplying to the constructor a List<T>
(and not List<Node<T>>
), you probably want
Node(T data, int h) {
this.tower = new ArrayList<Node<T>>(Collections.nCopies(h, new Node<T>(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)->data) // what Collections.nCopies does
.map(Node::new) // but here we'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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论