2013-02-23 42 views
1

我有一個遞歸的方法,打印出命令行中的值。我需要創建一個臨時數組,並使用Swing顯示結果。如何在每次循環時創建數組並存儲值?如何在java中的遞歸函數中創建一個數組

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更適合這個。