简体   繁体   English

如何在java中的递归函数中创建数组

[英]How to create an array in recursive function in java

I have a recursive method that prints out the values in command line. 我有一个递归方法,在命令行中打印出值。 I need to create a temp array with the result an display it using Swing. 我需要创建一个临时数组,其结果是使用Swing显示它。 how do I create the array and store the values each time it loops ? 如何创建数组并在每次循环时存储值?

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

so instead of JOptionPane I have only onew window with the list of names and can reuse later. 因此,我只有一个带有名称列表的窗口,而不是JOptionPane,可以在以后重复使用。

A general tactic for building something recursively is to use a Collecting Parameter . 递归构建内容的一般策略是使用收集参数

This can be applied in your case by: 这可以通过以下方式应用于您的情况:

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
}

Of course, if you really want it in an array, you can convert it afterwards: 当然,如果你真的想要它在数组中,你可以在之后转换它:

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

With an unknown size, arrays are painful, so a List works better for this. 对于未知的大小,数组是痛苦的,因此List更适合这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM