2013-02-23 3 views
1

명령 줄에 값을 출력하는 재귀 적 메서드가 있습니다. temp 배열을 만들고 Swing을 사용하여 결과를 표시해야합니다. 루프를 만들 때마다 배열을 만들고 값을 저장하는 방법은 무엇입니까?자바에서 재귀 함수로 배열을 만드는 방법

static void listSnapshots(VirtualMachine vm) 
    { 
     if(vm == null) 
    { 
     JOptionPane.showMessageDialog(null, "Please make sure you selected existing vm"); 
     return; 
    } 

    VirtualMachineSnapshotInfo snapInfo = vm.getSnapshot(); 
    VirtualMachineSnapshotTree[] snapTree = snapInfo.getRootSnapshotList(); 
    printSnapshots(snapTree); 
} 

static void printSnapshots(VirtualMachineSnapshotTree[] snapTree) 
{ 
    VirtualMachineSnapshotTree node; 
    VirtualMachineSnapshotTree[] childTree; 

    for(int i=0; snapTree!=null && i < snapTree.length; i++) 
    { 
     node = snapTree[i]; 
     System.out.println("Snapshot name: " + node.getName()); 
     JOptionPane.showMessageDialog(null, "Snapshot name: " + node.getName()); 
     childTree = node.getChildSnapshotList(); 

     if(childTree != null) 
     { 

      printSnapshots(childTree); 
     } 
    }//end of for 

그래서 JOptionPane 대신 이름 목록이있는 새 창만 있고 나중에 재사용 할 수 있습니다.

답변

3

재귀 적으로 무언가를 구축하는 일반적인 방법은 Collecting Parameter을 사용하는 것입니다. 당신이 정말로 배열을 원하는 경우

static List<String> listSnapshotNames(VirtualMachineSnapshotTree[] snapTree) { 
    ArrayList<String> result = new ArrayList<String>(); 
    collectSnapshots(snapTree, result); 
    return result; 
} 

static void collectSnapshots(VirtualMachineSnapshotTree[] snapTree, List<String> names) 
{ 
    VirtualMachineSnapshotTree node; 
    VirtualMachineSnapshotTree[] childTree; 

    for(int i=0; snapTree!=null && i < snapTree.length; i++) 
    { 
     node = snapTree[i]; 
     names.add(node.getName()); 
     childTree = node.getChildSnapshotList(); 

     if(childTree != null) 
     { 

      collectSnapshots(childTree, names); 
     } 
    }//end of for 
} 

는 물론, 당신이 나중에 변환 할 수 있습니다 :

을하여 경우에 적용 할 수있는 알 수없는 크기와

static String[] getSnapshotNames(VirtualMachineSnapshotTree[] snapTree) { 
    List<String> result = listSnapshotNames(snapTree); 
    return result.toArray(new String[0]); 
} 

, 배열은 고통 스럽기 때문에 List이 더 잘 작동합니다.

관련 문제