user8922738
user8922738

Reputation: 25

ArrayList accessor method returns no values

This is my first program that I am making out of my own class. It is meant to perform a single-transferable election; right now I need to get an ArrayList<Candidate> of Candidate objects. Inside the constructor, the process works just fine; however, once I try to use an accessor method an empty ArrayList is returned. Here is the code:

import java.util.*;
public class Election {

    public ArrayList<Candidate> candidates = new ArrayList<Candidate>();

    Election(int numVotes) {
        String name;
        ArrayList<Candidate> candidates = new ArrayList<Candidate>();
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter the candidates you want in the election.");
        System.out.println("Enter -1 once you have listed all the candidates.");
        System.out.print("Start entering candidates: ");
        name = keyboard.nextLine();
        while (!name.equals("-1")) {
            candidates.add(new Candidate(name));
            System.out.print("Ok, enter a new candidate or -1: ");
            name = keyboard.nextLine();

        }

        //Works fine here
    }

    public ArrayList<Candidate> getCandidateList() {   
        //Keeps returning empty list
        //System.out.println(candidates);
        return this.candidates;    
    }
} 

Upvotes: 0

Views: 1083

Answers (3)

Sacha
Sacha

Reputation: 332

You are creating a new ArrayList variable in your constructor, instead you should do this.candidates = new ArrayList<Candidate>();

Also, it's bad practice to have all your logic in your constructor, you should instead make an addCandidates() method

Upvotes: 0

Ahmad Shahwan
Ahmad Shahwan

Reputation: 1957

In this line:

ArrayList<Candidate> candidates = new ArrayList<Candidate>();

you define a local variable that hides the class member. Drop that line.

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

public ArrayList<Candidate> candidates = new ArrayList<Candidate>();
Election(int numVotes)
{
    String name;
    ArrayList<Candidate> candidates = new ArrayList<Candidate>();
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You are creating a different arraylist and "shadowing" the candidates member variable. It should be

    this.candidates = new ArrayList<Candidate>();

Upvotes: 2

Related Questions