2014-07-07 2 views
0

재귀 함수가 있지만 ArrayList에 이전 데이터를 추가 (저장)하고 싶습니다.재귀 함수 - ArrayList 저장 Java

나는 현재이 일을하고 있지만 저장하지 않습니다 : 당신의 도움에 대한

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; 
} 

감사합니다!

답변

2

코드에서 메서드에 대한 각 재귀 호출은 자신의 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 반환 유형을 가질 수 있습니다.

+0

도움 주셔서 감사합니다. 잘 작동합니다 :-) – user3240520

2

메서드 내에서 새 ArrayList를 만듭니다. ArrayList<String> listTokenFunction = new ArrayList<String>();이므로 '오래된'목록은 사라지고 항목을 광고하면 항상 첫 번째 항목이됩니다. 클래스 변수로 메소드 외부에서 Arraylist를 초기화 해보십시오.