Java 如何从方法返回一个数组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3748070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:19:27  来源:igfitidea点击:

How to return an arraylist from a method

javamethodsarraylistreturn-value

提问by Luron



I need help. For this specific method. I am trying to get it to return an arraylist that I tokenized.

我需要帮助。对于这个特定的方法。我试图让它返回一个我标记化的数组列表。

public ArrayList read (){

  BufferedReader inputStream = null;
  try {
    inputStream = new BufferedReader(new FileReader("processes1.txt"));
    String l;
    while ((l = inputStream.readLine()) != null) {

      ArrayList<String> tokens = new ArrayList<String>();

      Scanner tokenize = new Scanner(l);
      while (tokenize.hasNext()) {
        tokens.add(tokenize.next());
      }
      return tokens;
    }
  } catch(IOException ioe){
    ArrayList<String> nothing = new ArrayList<String>();
    nothing.add("error1");
    System.out.println("error");
    //return nothing;
  }
  return tokens;
}

What am I doing wrong?!

我究竟做错了什么?!

采纳答案by Mitch Dempsey

At the very end you are doing return tokensbut that variable was defined INSIDE the try block, so it is not accessible outside of it. You should add:

最后,您正在执行此操作,return tokens但是该变量是在 try 块内部定义的,因此在它外部无法访问。你应该添加:

ArrayList<String> tokens = new ArrayList<String>();

ArrayList<String> tokens = new ArrayList<String>();

to the top of your method, just under the BufferedReader.

到方法的顶部,就在 BufferedReader 下。

回答by Aurojit Panda

Try returning ArrayList which is the more appropriate return type in this case. Generic types aren't related to each other the way your example seems to be using them.

尝试返回 ArrayList,这是在这种情况下更合适的返回类型。泛型类型与您的示例似乎使用它们的方式无关。

回答by venky

It is probably an error in your main method somewhere. Are you instantiating the class and calling the method read() on it?

这可能是您的主要方法中某处的错误。您是否正在实例化该类并对其调用 read() 方法?

回答by Bindumalini KK

Try this:

尝试这个:

public ArrayList read (){

          File text = new File("processes1.txt");

              ArrayList<String> tokens = new ArrayList<String>();

              Scanner tokenize;
            try {
                tokenize = new Scanner(text);
                while (tokenize.hasNext()) {

                      tokens.add(tokenize.next());
                  }

                }

            catch(IOException ioe){
                ArrayList<String> nothing = new ArrayList<String>();
                nothing.add("error1");
                System.out.println("error");
                //return nothing;
              }
             return tokens;

    }}