gpt4 book ai didi

java - 添加到带有参数的类对象的 ArrayList 中?

转载 作者:行者123 更新时间:2023-12-01 06:42:53 25 4
gpt4 key购买 nike

我有一个构造函数:

Candidate(String name, int numVotes)
{
this.name = name;
this.numVotes = numVotes;
}

我已经制作了该类的 ArrayList:

List <Candidate> election = new ArrayList<Candidate>();

我正在尝试将此类的多个对象添加到 ArrayList 中。我已经尝试过这个,但它不起作用:

election.add("John Smith", 5000);
election.add("Mary Miller", 4000);

它抛出一个编译器错误,指出:

The method add(int, Candidate) in the type List<Candidate> is not applicable for the arguments (String, int)

我做错了什么?任何帮助将不胜感激。

最佳答案

选举 ArrayList 只知道它保存 Candidate 对象,因此这是您唯一可以添加的东西。不是字符串,不是数字,而是候选者。

因此您需要显式地将 Candidate 对象添加到 ArrayList 中:

election.add(new Candidate("John Smith", 5000));

关于java - 添加到带有参数的类对象的 ArrayList 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36635948/

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