java - 递归函数——保存ArrayList Java

标签 java recursion arraylist

我有一个递归函数,但我想在 ArrayList 中添加(并保存)以前的数据。

我目前正在这样做,但它没有保存:

  private ArrayList<String> checkNextPage(String urlGoogleToken){

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

    try
    {
        /* I AM DOING SOME STUFF */

        if (jsonObj.has("next_page_token")){
            String next_page_token = (String) jsonObj.get("next_page_token");
            listTokenFunction.add(next_page_token); // I WANT TO SAVE THIS LIST
            String result = urlGoogleToken.split("&pagetoken=")[0];
            String urlGoogleMaps2 = result+"&pagetoken="+next_page_token; 
            checkNextPage(urlGoogleMaps2); // CALL THE FUNCTION
        } else {
            System.out.println("ELSE");
        }
    } catch (Exception e) {
            e.printStackTrace();
       }

    return listTokenFunction;
}

感谢您的帮助!

最佳答案

在您的代码中,对该方法的每个递归调用都会创建自己的 ArrayList 作为局部变量。解决此问题的一种方法是更改​​方法,使其采用(最初为空的)ArrayList 作为输入并填充它。每个递归调用都会将列表作为输入并添加到其中。

private void checkNextPage(ArrayList<String> listTokenFunction, String urlGoogleToken){

   // initialize if null
   if(listTokenFunction == null) {
       listTokenFunction = new ArrayList<String>();
   }

   try
   {
       /* I AM DOING SOME STUFF */

       if (jsonObj.has("next_page_token")){
          String next_page_token = (String) jsonObj.get("next_page_token");
          listTokenFunction.add(next_page_token); // I WANT TO SAVE THIS LIST
          String result = urlGoogleToken.split("&pagetoken=")[0];
          String urlGoogleMaps2 = result+"&pagetoken="+next_page_token; 
          checkNextPage(urlGoogleMaps2, listTokenFunction); // CALL THE FUNCTION
       } else {
          System.out.println("ELSE");
       }
   } catch (Exception e) {
          e.printStackTrace();
   }

}

该方法可以有一个 void 返回类型,因为列表将在内部填充,并且不需要返回它。

关于java - 递归函数——保存ArrayList Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616332/

相关文章:

java - 类型安全配置 : encryption/obfuscation of sensitive values in memory

java类的初始化顺序,它是如何工作的?

java - 为什么字符串数组可以分配给对象数组,但字符串数组列表不能分配给对象数组列表?

java - 显示\t\n为节点的原因是什么?

java - 使用递归方法进行三元搜索

Python - 归并排序递归算法

python - 递归地浏览和抓取网页

Java ArrayList 和 FileReader

java - 使用数字对对数组进行排序

java - Telnet Java 代码可以在 Windows 中运行,但不能在 Unix 中运行