0

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.

1 Answer 1

10

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.