简体   繁体   中英

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 . 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. The utility class Arrays has methods to do this.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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