Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: variable length parameters as list for recursion

I would something like the following recursive method:

private Node getElementRec(Node currentNode, String ... names) {
    if (null == names || names.length == 0)
        return currentNode;
    else {
        Node child = currentNode.getChildWithName(names[0]);
        return getElementRec(child, namesAux.subList(1, names[1,]));
    }
}

Since variable length Java parameters (here names) are arrays, I cannot make something like names.sublist(1, names.size()) Although it would be rather inefficient, I've tried to convert the array to a list and then pass it to the method, but it doesn't accept a list

So the question is: is it possible in Java to do recursion over a variable length parameter (Type ... parameter)? Something like I showed is possible?

Thanks

like image 610
juanmirocks Avatar asked Apr 25 '26 03:04

juanmirocks


1 Answers

You can use the copyOfRange function from the Arrays class to pass to the function

Arrays.copyOfRange(names, 1, names.length)

Another way to avoid copying would be to modify your function to accept start and end index:

private Node getElementRec(Node currentNode, int start, int end, String ... names) {
    if (null == names || start >= end || start < 0 || end > names.length)
        return currentNode;
    else {
        Node child = currentNode.getChildWithName(names[start]);
        return getElementRec(child, start+1, end, names);
    }
}
like image 143
Petar Ivanov Avatar answered Apr 26 '26 15:04

Petar Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!