【问题标题】:Can't use arraylist due to "static referense due to non-static method" (java) [duplicate]由于“由于非静态方法导致的静态引用”(java)而无法使用arraylist
【发布时间】:2014-06-12 18:05:24
【问题描述】:

我正在为我正在处理的任务编写一个简单的程序。但是,当我尝试将 ArrayList“员工”移到主方法之外时,出现错误“无法对非静态字段员工进行静态引用”。

有效的代码:

public class X{

public static void main(String[] args){

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

    while(i<6){
        int skill = generator.nextInt(5);
        int id = generator.nextInt(100);  //for this purpose we will never 
        Employee newFresher = new Employee(id, skill);
        employees.add(newFresher);
        System.out.println(newFresher);
        i++;
    }
}

public void getCallHandler(){
   //CODE THAT REALLY NEEDS TO SEE THAT ARRAYLIST
}
}

引发错误“无法进行静态引用”的代码:

public class X{

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

public static void main(String[] args){


    while(i<6){
        int skill = generator.nextInt(5);
        int id = generator.nextInt(100);  //for this purpose we will never 
        Employee newFresher = new Employee(id, skill);
        employees.add(newFresher);
        System.out.println(newFresher);
        i++;
    }
}

public void getCallHandler(){
   //CODE THAT REALLY NEEDS TO SEE THAT ARRAYLIST
}
}

我只是不知道是什么原因造成的。非常感谢您的帮助。

PS:忽略奇怪的缩进。它只是stackoverflow格式化它很奇怪。

【问题讨论】:

标签: java exception static-methods


【解决方案1】:

main() 方法是一个静态方法,您只能从那里访问静态字段。所以你在这里有两个选择:

  1. 只需将 employees 字段标记为静态,然后您就可以直接从您的 main 方法访问它。
  2. 或者,如果您不将该字段设为静态,那么它仍然是一个实例字段。在这种情况下,将 main 方法的所有逻辑移动到实例方法 (processEmployees()) 中,并创建类的实例 (X x = new X();),然后调用此方法 (x.processEmployees())。

【讨论】:

    【解决方案2】:

    问题是,员工列表不是静态的,但您在静态方法中使用它。你不能这样做,静态意味着这个类的每个实例一个,而非静态意味着每个实例一个。要么让员工静态,要么不在静态方法中使用它,在静态方法中执行new X()之类的操作,在构造函数中使用员工:

    public X() {
       // use employees here!
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 2013-06-30
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 2015-06-20
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多