mlilley
mlilley

Reputation: 407

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.

Upvotes: 0

Views: 592

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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));

Upvotes: 10

Related Questions