gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:48:09 25 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 如何在java中的递归函数中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15043264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com