You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Election类中ArrayList访问器方法返回空值问题求助

问题分析与解决

你碰到的问题其实是典型的**变量遮蔽(Variable Shadowing)**问题!

看你的代码:类的成员变量已经定义了public ArrayList<Candidate> candidates = new ArrayList<Candidate>();,但在构造函数里,你又重新声明了一个同名的局部变量ArrayList<Candidate> candidates = new ArrayList<Candidate>();。这就导致构造函数里所有对candidates的操作,都是在操作这个局部的列表,而类的成员变量candidates自始至终都没被添加过任何元素,所以调用getCandidateList()返回空列表也就不奇怪了。

修正后的代码

只需要删掉构造函数里重新声明candidates的那一行,直接使用类的成员变量即可:

import java.util.*;

public class Election {
    public ArrayList<Candidate> candidates = new ArrayList<Candidate>();

    Election(int numVotes) {
        String name;
        // 移除局部变量的声明,直接使用类成员变量
        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();
        }
    }

    public ArrayList<Candidate> getCandidateList() {
        return this.candidates;
    }
}

额外优化建议

从面向对象的封装原则来说,建议把成员变量candidates设置为私有(private),然后通过getCandidateList()来访问,这样可以避免外部直接修改这个列表,提高代码的安全性和可维护性:

import java.util.*;

public class Election {
    private ArrayList<Candidate> candidates = new ArrayList<Candidate>(); // 改为私有

    Election(int numVotes) {
        String name;
        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();
        }
    }

    public ArrayList<Candidate> getCandidateList() {
        // 返回列表的副本,避免外部直接修改原列表
        return new ArrayList<>(this.candidates);
        // 也可以返回不可修改的列表:return Collections.unmodifiableList(this.candidates);
    }
}

内容的提问来源于stack exchange,提问作者user8922738

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:41:44