【问题标题】:How to create an array in recursive function in java如何在java中的递归函数中创建一个数组
【发布时间】:2013-02-23 17:16:40
【问题描述】:

我有一个递归方法,可以在命令行中打印出值。我需要创建一个带有结果的临时数组,并使用 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,以后可以重复使用。

【问题讨论】:

    标签: java arrays swing recursion


    【解决方案1】:

    递归构建东西的一般策略是使用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 更适合这个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-13
      • 2017-02-13
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多