[英]Adding to an ArrayList of a class object with parameters?
我有一个构造函数:
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对象显式添加到ArrayList中:
election.add(new Candidate("John Smith", 5000));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.