有没有办法将ArrayList保持为局部变量?

huangapple go评论62阅读模式
英文:

Is there a way to keep the ArrayList as a local variable?

问题

public static ArrayList<String> searchFiles(File currentFolder) throws NotDirectoryException {
    ArrayList<String> result = new ArrayList<String>();
    if (!currentFolder.isDirectory())
        throw new NotDirectoryException("File is not a directory");
    File[] direct = currentFolder.listFiles();
    if (direct != null) {
        for (int i = 0; i < direct.length; i++) {
            if (direct[i].isDirectory())
                searchFiles(direct[i]);
            if (direct[i].isFile() && !direct[i].isHidden())
                result.add(direct[i].getName());
        }
    }
    return result;
}

这段代码的目的是递归地搜索所有目录和子目录,然后将符合条件的文件添加到一个 ArrayList 中。如果将 ArrayList 声明从方法中移除,改为作为全局变量,它会正确地将所有目录中的文件添加到 ArrayList 中。但如果将其保留为局部变量,它只会添加根目录中的文件,而不会添加其他内容。有没有办法在保持 ArrayList 作为局部变量的同时使代码正常工作呢?

英文:
public static ArrayList&lt;String&gt; searchFiles(File currentFolder) throw NotDirectoryException {
    ArrayList&lt;String&gt; result = new ArrayList&lt;String&gt;();
    if(!currentFolder.isDirectory())
      throw new NotDirectoryException(&quot;File is not a directory&quot;);
    File[] direct = currentFolder.listFiles();
    if(direct!=null) {
      for (int i = 0; i&lt; direct.length; i++){
        if(direct[i].isDirectory())
          searchFiles(direct[i]);
        if(direct[i].isFile()&amp;&amp;!direct[i].isHidden())
        result.add(direct[i].getName());
      }
    }
  return result;
  }

The purpose of this code is to search through all directories and sub directories and then add the eligible files into an arraylist recursively. The code works fine if I remove the ArrayList declaration from the method and put it instead as a global varible, it will correctly add all files in the directories into the arraylist. If i keep it as a local variable, it only adds the files in the root folder and nothing else. Is there a way to keep the ArrayList as a local variable while making the code work?

答案1

得分: 2

你可以将 ArrayList 传递给递归调用,如下所示:

public static ArrayList<String> searchFiles(File currentFolder, ArrayList<String> result) throws NotDirectoryException {
    if (!currentFolder.isDirectory()) 
        throw new NotDirectoryException("File is not a directory");
    File[] direct = currentFolder.listFiles();
    if (direct != null) {
        for (int i = 0; i < direct.length; i++) {
            if (direct[i].isDirectory())
                searchFiles(direct[i], result);
            if (direct[i].isFile() && !direct[i].isHidden())
                result.add(direct[i].getName());
        }
    }
    return result;
}
注意当您将 `result` 声明为局部变量时在方法返回后它将被销毁为了保留其值您可以在递归调用方法时将其作为参数传递


<details>
<summary>英文:</summary>

You can pass the `ArrayList` to the recrsive call as shown below: 

    public static ArrayList&lt;String&gt; searchFiles(File currentFolder, ArrayList&lt;String&gt; result) throw NotDirectoryException {
    	if(!currentFolder.isDirectory()) 
    		throw new NotDirectoryException(&quot;File is not a directory&quot;);
    	File[] direct = currentFolder.listFiles();
    	if(direct!=null) {
    		for (int i = 0; i&lt; direct.length; i++){
    			if(direct[i].isDirectory())
    				searchFiles(direct[i], result);
    			if(direct[i].isFile()&amp;&amp;!direct[i].isHidden())
    				result.add(direct[i].getName());
    		}
    	}
    	return result;
    }
Note that when you declare `result` as a local variable, it will be destroyed after the method will return. In order to preserve its value, you can pass it as a parameter while calling the method recursively.

</details>



# 答案2
**得分**: 1

你所需做的就是正确地在递归中使用`searchFiles`的返回值例如不要再使用

    searchFiles(direct[i]);

而应该使用

    result.addAll(searchFiles(direct[i]));

在其他答案中递归地传递可变的`ArrayList`更高效但更加令人困惑最好配合一个没有`ArrayList`参数的方法的公共重载此外这将违反你问题的标题标题指明`ArrayList`应保持为局部变量

<details>
<summary>英文:</summary>

All you need to do is properly use the return value of `searchFiles` in the recursion.  For example, instead of

    searchFiles(direct[i]);

write

    result.addAll(searchFiles(direct[i]));

Passing the mutable `ArrayList` recursively in other answers is more efficient, but more confusing, and is best paired with a public overload of the method without the `ArrayList` parameter.  Additionally, this would violate your question&#39;s title, which specifies that the `ArrayList` should remain a local variable.

</details>



# 答案3
**得分**: 0

传入这个ArrayList原始调用者会传入一个新的ArrayList()

<details>
<summary>英文:</summary>

Pass in the arraylist. The original caller would pass in a new ArrayList()

</details>



huangapple
  • 本文由 发表于 2020年10月3日 04:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64177955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定