当我使用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);
}
}
}
}
答案 0 :(得分:0)
用以下内容替换您的功能。
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;
}
答案 1 :(得分:-1)
您必须返回for封锁之外。否则,您将返回一个元素。您还需要在每个循环中重新实例化该列表。
答案 2 :(得分:-1)
尝试此代码。只有几处变化。我在移动或删除代码的地方加上了备注。
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);
}
}
}
}