简体   繁体   English

java使用递归打印项目列表似乎效率低下

[英]java print list of items using recursion seems inefficient

I am doing a pretty basic assignment. 我正在做一个非常基本的任务。 "Use recursion to print the values of a list" and I came up with the code below, but as it passes the list EVERY time it calls itself I wondered if there is a better way. “使用递归来打印列表的值”,我想出了下面的代码,但是当它每次通过列表时都会通过列表,所以我想知道是否有更好的方法。 Any advice please? 有什么建议吗?

public class RecurList {

public static void main(String[] args) {
    int[] list = {8,7,9,10,56};

    int ix = list.length;
    int sumNow = ShowNext(ix, 0, list);  // initial call -> sum is 0

    System.out.println("Recursion total is " + sumNow);
}   
    public static int ShowNext(int inx, int sum, int[] lst) {
        if (inx == 0) return sum;
        int item = lst[inx - 1];
        sum += item;
        System.out.println("inx:" + inx + " item:" + item + " sum:" + sum);
        return ShowNext(inx - 1, sum, lst);
    }

} }

Please read and follow Java Naming Conventions . 请阅读并遵守Java命名约定 Start your method names with a lowercase letter. 用小写字母开头的方法名称。

"Use recursion to print the values of a list" “使用递归来打印列表的值”

You failed that assignment since you're using an array instead of a list. 由于您使用的是数组而不是列表,因此分配失败。

it passes the list EVERY time it calls itself I wondered if there is a better way. 每当它自称它会通过列表时,我想知道是否有更好的方法。

There are two solutions to this problem. 有两个解决方案。

The more intentional approach is what @Prune suggested: shorten the list (which is an array in your case) by one element. @Prune建议使用更故意的方法:将列表(在您的情况下为数组)缩短一个元素。 The utility class Arrays has methods to do this. 实用程序类Arrays具有执行此操作的方法。

The lesser "recursive" style is to make the array a class member and remove it from the methods parameter list: 较小的“递归”样式是使数组成为类成员,并将其从方法参数列表中删除:

 public class RecurList {
    static int[] list; 
 public static void main(String[] args) {
    list = {8,7,9,10,56};

    int ix = list.length;
    int sumNow = ShowNext(ix, 0);  // initial call -> sum is 0

    System.out.println("Recursion total is " + sumNow);
  }   
  public static int ShowNext(int inx, int sum) {
        if (inx == 0) return sum;
        int item = lst[inx - 1];
        sum += item;
        System.out.println("inx:" + inx + " item:" + item + " sum:" + sum);
        return ShowNext(inx - 1, sum);
    }
}

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

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