简体   繁体   中英

Adding to an ArrayList of a class object with parameters?

I have a constructor:

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

I've made an ArrayList of that class:

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

I'm trying to add multiple objects of this class to the ArrayList. I've tried this, but it doesn't work:

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

It's throwing a compiler error stating:

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

What am I doing wrong? Any help would be appreciated.

The election ArrayList only knows that it holds Candidate objects, and so that is the only thing you can add. Not Strings, not numbers, but Candidates.

So you need to explicitly add Candidate objects to the ArrayList:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM