AnswerBun.com

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

Answered by Alberto Sinigaglia on January 5, 2022

Add your own answers!

Related Questions

How do I debug SwiftUI AttributeGraph cycle warnings?

5  Asked on December 30, 2021 by sindre-sorhus

       

RTD client in Python

1  Asked on December 30, 2021 by hunk

     

How to remove mongo specific fields from result (NodeJS, Mongoose)

5  Asked on December 30, 2021 by ararat-harutyunyan

     

Problem with ionic framework How can I solve?

0  Asked on December 30, 2021 by scar-fuentes

         

Random Forest Output

0  Asked on December 30, 2021 by charles-biwer

     

How to shift range of cells to unify values in rows

2  Asked on December 30, 2021 by jozef

 

Ask a Question

Get help from others!

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