user10018802
user10018802

Reputation:

Java Recursively add to list

Everything seems fine, but there's an error with this line:

return new ArrayList<Integer>(Arrays.asList(i, FACTORISATION(n/i)));

The error is: The constructor ArrayList(Arrays.asList(i), ArrayList) is undefined

I understand that the error says the the Array's asList method doesn't take an ArrayList, but then how can I add the items returned by FACTORISATION in the list? This recursion is really messing with my head

Upvotes: 1

Views: 1711

Answers (1)

Willis Blackburn
Willis Blackburn

Reputation: 8204

Java isn't really a functional programming language, so writing functional code like this tends to be a little clunky.

You want something like this:

public static List<Integer> FACTORISATION(int n) {
    if (PRIME(n)) {
        // return a one-element array
        return Collections.singletonList(n);
    } else {
        // find a prime divisor, p
        for (int i = 2; i < Math.sqrt(n); i++) {
            List<Integer> newList = new ArrayList<>();
            newList.add(i);
            newList.addAll(FACTORISATION(n/i));
            return newList;
        }
        return Collections.emptyList();
    }
}

Note I changed to return interface type List<Integer> and also to use Collections.singletonList.

If you can use Guava then try ImmutableList, which is a little more elegant.

public static List<Integer> FACTORISATION(int n) {
    if (PRIME(n)) {
        // return a one-element array
        return ImmutableList.of(n);
    } else {
        // find a prime divisor, p
        for (int i = 2; i < Math.sqrt(n); i++) {
            return new ImmutableList.Builder<Integer>()
                .add(i)
                .addAll(FACTORISATION(n/i))
                .build();
        }
        return Collections.emptyList();
    }
}

Upvotes: 2

Related Questions