使用参数添加到类对象的ArrayList?

Mic*_*ley 0 java arraylist

我有一个构造函数:

Candidate(String name, int numVotes)
{
    this.name = name;
    this.numVotes = numVotes;
}
Run Code Online (Sandbox Code Playgroud)

我已经制作了该类的ArrayList:

List <Candidate> election = new ArrayList<Candidate>();
Run Code Online (Sandbox Code Playgroud)

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

election.add("John Smith", 5000);
election.add("Mary Miller", 4000);
Run Code Online (Sandbox Code Playgroud)

它抛出一个编译器错误说明:

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

我究竟做错了什么?任何帮助,将不胜感激.

Hov*_*els 10

选举ArrayList只知道它拥有Candidate对象,因此这是你唯一可以添加的东西.不是字符串,不是数字,而是候选人.

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

election.add(new Candidate("John Smith", 5000));
Run Code Online (Sandbox Code Playgroud)