Java – traverses the array in reverse without minus sign

I was asked this question in today's interview I'm sure it's a very simple technique, but I can't think of it How do I traverse a simple java array from one end to the other (for example, to aggregate the sum of all values from right to left) without using the minus (–) symbol (so there is no I –, or the like in the loop)?

Editor: I'm pretty sure it should be a technique that doesn't involve Java specific structures (such as collections) Unfortunately, I thought I would think of it myself, so I didn't ask what the answer was:/

Solution

Recursion is an option:

int[] numbers = {0,1,2,3,4,5,6,7,8,9,10};

public void traverseReversed(int[] a) {
    traverseReversed(a,0);
}

private void traverseReversed(int[] a,int i) {
    if ( i + 1 < a.length ) {
        // Traverse the rest of the array first.
        traverseReversed(a,i+1);
    }
    System.out.println(a[i]);
}

public void test() throws Exception {
    System.out.println("Hello World!");
    traverseReversed(numbers);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>