Java递归添加到列表

时间:2019-07-02 02:16:40

标签: java

一切似乎都很好,但是此行有错误:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="header">
            <span class="siteheader">ChubbyMan'sMath.com</span>  
            <div class="title">Area Calculator</div>
    </div>

    <p class="question">What shape do you want to find the area of?</p>
    <p id="n1" onclick="showForm();">1. Square</p> <!-- answer --> <p id="squareanswer">The area is 100.</p>
    <p id="n2">2. Rectangle</p>
    <p id="n3">3. parallelogram</p>
    <p id="n4">4. Circle</p>
    <p id="n5">5. Triangle</p>
    <p id="n6">6. Rhombus</p>
    <p id="n7">7. Trapezoid</p>

    <form name="squareform" id="squareform">
        <input id="squareinput"   type="text" placeholder="x">
        <input type="submit" value="Submit" id="squarebutton" onclick="square()">
    </form>

</body>
<script src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:900&display=swap" rel="stylesheet">
</html>

错误是:构造函数ArrayList(Arrays.asList(i),ArrayList)未定义

我知道该错误表明Array的asList方法没有采用ArrayList,但是如何在列表中添加FACTORISATION返回的项目?这种递归真的让我很头疼

1 个答案:

答案 0 :(得分:3)

Java并不是真正的功能编程语言,因此编写这样的功能代码往往有些笨拙。

您想要这样的东西:

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

请注意,我更改为返回接口类型List<Integer>,也使用了Collections.singletonList

如果您可以使用番石榴,请尝试ImmutableList,它稍微优雅一点。

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