ArrayList constructor undefined when using nCopes(int, generic)

Stack Overflow Asked by vzdiegocm on January 5, 2022

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)); = data;

Why is it giving me the following error:

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

2 Answers

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()); = data;

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

Answered by Sean Patrick Floyd on January 5, 2022

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))); = data;

Answered by Alberto Sinigaglia on January 5, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP