How do you add to an ArrayList using generics?

Victoria Li :

I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.

import java.util.ArrayList;

public class Ballot {
    private ArrayList<Candidate> ballot;
    private String officeName;

    public Ballot(String officeName) {
        this.officeName = officeName;
        ArrayList<Candidate> ballot = new ArrayList<Candidate>();
    }

    public String getOfficeName() {
        return officeName;
    }

    public void addCandidate(Candidate c) {
        ballot.add(c);
    }

    public ArrayList<Candidate> getCandidates() {
        return ballot;
    }

    public static void main(String[] args) {
        Ballot b = new Ballot("Election");
        b.addCandidate(new Candidate("Sarah", "President"));
        System.out.println(b);
    }
}

When I try to run the document, it throws a NullPointerException. What am I doing wrong?

Mureinik :

The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:

public Ballot(String officeName) {
    this.officeName = officeName;
    ballot = new ArrayList<Candidate>(); // Here!
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25093&siteId=1