[英]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.