簡體   English   中英

我的ArrayList不返回所有元素

[英]My ArrayList Not Returning all the elements

當我使用System.out.println靜態方法時,下面的Java程序將顯示ArrayList中的所有元素。 但是,當我在方法中返回列表時,它僅在ArrayList中顯示一個元素。 對於出現錯誤的情況,我將提供一些指導:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileProcessor {  
  static List<String> theList = null;

  /**
   * 
   * @return List
   */
  public static List<String> processFiles() {      
    try {    
      File f = new File("/Data/fileDump");
      String[] listOfFiles = f.list();

      for(String eachFile: listOfFiles) {  
        if(eachFile.startsWith("hawk") == true) { 
          theList = new ArrayList<>(); 
          theList.add(eachFile); 
          return theList;
        }
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
    return theList;
  }


  public static void main(String[]args) {
    List<String> dataList = FileProcessor.processFiles(); 
    for(String strg: dataList) {
      if(strg != null) {
        System.out.println(strg);
      }
    }
  }
}

用以下內容替換您的功能。

      public static List<String>  processFiles() { 
          List<String> theList = null;
          try {    

             File  f = new File("/Data/fileDump");
             String[] listOfFiles = f.list();
             theList = new ArrayList<>(); // initialisation moved outside of loop
             for(String eachFile:   listOfFiles) {  
                 if(eachFile.startsWith("hawk") == true){              
                    theList.add(eachFile); 
               }
             }
             return theList;// return statement moved outside of the loop

          } catch(Exception e) {
             e.printStackTrace();
          }
        return theList;
       }

您必須返回for block以外。 否則,您將返回一個元素。 您還需要在每個循環中重新實例化該列表。

試試這個代碼。 只有幾處變化。 我在移動或刪除代碼的地方加上了備注。

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileProcessor {  
static  List<String> theList = null;





 /**
  * 
  * @return List
  */
 public static List<String>  processFiles() {      

      try {    


          File  f = new File("/Data/fileDump");

          String[] listOfFiles = f.list();
          theList = new ArrayList<>();  /* Move this here */
          for(String eachFile:   listOfFiles) {  
             if(eachFile.startsWith("hawk") == true){
                theList.add(eachFile);

               /* Deleted the extra return. The one at the end will handle it. */

             }
          }

      } catch(Exception e) {


         e.printStackTrace();
      }
    return theList;
   }


    public static void main(String[]args){
     List<String> dataList = FileProcessor.processFiles(); 
     for(String strg: dataList){
         if(strg != null){
            System.out.println(strg);
         }
     }


    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM