gpt4 book ai didi

java - 模板构造函数,并在主类中创建一个对象

转载 作者:行者123 更新时间:2023-11-29 08:26:07 26 4
gpt4 key购买 nike

这是构造函数的样子。

public Polinom(ArrayList<Integer> koeficient)
{
this.koeficienti = koeficienti;
}

这就是我创建数组并插入元素的方式。

int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = input.nextInt();
}

当我尝试创建这样的对象时:

Polinom arr3 = new Polinom(arr);

它告诉我“构造函数 Polinom(int[]) 未定义。我非常了解 Java 编程语言,但熟悉 C++,但我对语法有很大的疑问。

最佳答案

int[] (int 的数组)不是 ArrayList<Integer> ( List Integer ,特别是 ArrayList )。

您要么想要使用 List :

List<Integer> list = new ArrayList<>(n);
for(int i = 0; i < n; i++)
{
list.add(input.nextInt());
}

你的构造函数在哪里:

public Polinom(List<Integer> koeficienti)
{
// Generally not best practice to just remember the list passed in; instead,
// make a *defensive copy* of it so this instance doesn't share the list with
// the caller. (Or accept an immutable list.)
this.koeficienti = new ArrayList<Integer>(koeficienti);
}

编写您的构造函数,使其需要一个数组:

public Polinom(int[] entries)
{
this.koeficienti = new ArrayList<Integer>(entries.length);
for (int entry : entries) {
this.koeficienti.add(entry);
}
}

您可能会发现这些官方 Java 教程很有用:

关于java - 模板构造函数,并在主类中创建一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52952920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com