gpt4 book ai didi

Java从main方法之外的方法引用ArrayList

转载 作者:行者123 更新时间:2023-12-02 04:48:49 25 4
gpt4 key购买 nike

所以我有以下数组列表:

ArrayList <Employee> employees = new ArrayList<>();

在我的主要方法中,我创建它们的实例

public static void main(String[] args){
Employee test = new Manager("john doe", 1000); //manager is subclass

}

我有一个方法可以检查员工对象是否已经存在,equals 方法是在子类中定义的

public void addEmployee(Employee newEmployee){
for (int i = 0; i < employees.size(); i++){
if(newEmployee.equals(employees.get(i))){
.........
}
}
}

上面还有更多内容,但你明白了。我需要引用 ArrayList,但是如果我在 main 方法之外实例化数组列表,则无法向其中添加任何变量,从而出现错误“无法从静态上下文引用非静态方法”,这是有道理的,但我不知道如何使用该方法,因为我无法在主方法中声明它。

最佳答案

除非您想创建一个类来管理员工,否则您需要将方法和集合设为静态

static ArrayList <Employee> employees = new ArrayList<>();

public static void addEmployee(Employee newEmployee){
for (int i = 0; i < employees.size(); i++){
if(newEmployee.equals(employees.get(i))){
.........
}
}
}

@muued 有道理。除了ArrayList之外,java中还有其他数据结构。如有疑问,我会看这个:

enter image description here

关于Java从main方法之外的方法引用ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29441027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com