使用全局 LinkedList 变量确定静态方法

Determining static method with a global LinkedList variable

我很难决定何时将我的方法设为静态或非静态。有人告诉我创建一个全局 LinkedList 变量:

public static LinkedList list = new LinkedList();

现在,我编写了一个名为 read() 的方法来从文本文件中读取单词。然后我写了另一个方法 preprocessWord(word) 来检查这些单词是否以常量开头以将它们更改为小写。如果他们有这些条件,那么我将他们添加到 LinkedList 列表中:

  public void read(){
  ....
  while((nextLine = inFile.readLine())!= null){

    tokens = nextLine.trim().split("\s+");
    for(int i = 0; i < tokens.length; i++){
        word = tokens[i];
        word = preprocessWord(word);
          list.append(word);}
    }
  }
  ...
  }//read

但是,当我尝试从 main 方法调用 read() 时;

 public static void main(String[] args) {
  read();
  System.out.println(list);

 }//main

错误是我无法对非静态方法进行静态引用 read(),因此我尝试将方法 read()preprocessedWord() 更改为静态方法,但是随后words 没有像他们想象的那样在 preprocessedWord() 中更新。我真的不知道哪里可以使用静态,哪里不能,有人可以解释一下我的想法哪里出了问题吗?

通俗地说,当你定义一个非静态方法时,它只能在这个 class 的实例上调用。但是,在您的情况下,您需要 运行 这样的事情

public static void main(String[] args) {
  new YourClassName().read();
  System.out.println(list);

 }

然而,这样做意味着在您的读取方法中,您必须访问静态列表,如

YourClassName.list.append(word)

另一种方法也是将读取设为静态,因此在这种情况下,您的方法签名应该是

public static void read()

因为您的 read 方法不是静态的。除非你需要,否则不要使用静态字段。用于在同一 class 的所有对象之间共享引用。使您的列表成为非静态的甚至是本地的,并作为参数传递给后续方法调用