为什么会发生ArrayIndexOutOfBoundsException?

问题描述 投票:0回答:1
def change(amount: Int, coins: Array[Int]): Int = {
        val dp = Array[Int](amount + 1)
        dp(0) = 1
        for {
            coin <- coins
            i <- coin to amount
        } dp(i) += dp(i - coin)
        dp(n)
}


当我执行上述方法时,出现以下错误。

java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
    at Main$.$anonfun$change$2(HelloWorld.scala:9)

但是,当我使用 new 关键字初始化数组并执行它时,它执行得很好并且我得到了正确的输出。

为什么?

def change(amount: Int, coins: Array[Int]): Int = {
        val dp = new Array[Int](amount + 1)
        dp(0) = 1
        for {
            coin <- coins
            i <- coin to amount
        } dp(i) += dp(i - coin)
        dp(n)
}

我不知道我的理解是否正确,但我发现的唯一区别是提到了 new 关键字。所以我的问题是,上述方法中是否与数组初始化有任何联系来获取 ArrayIndexOutOfBoundExeption,如果有,它是什么?

我需要 Scala 编程方面的解释。

arrays scala dynamic-programming arrayindexoutofboundsexception
1个回答
0
投票
new Array(integer)

使用元素数量调用构造函数。它将创建一个大小为

integer
的数组,并用零填充。

Array(integer)

在 Array 伴随对象上调用

apply
方法 - 基本上是一个工厂方法,它创建一个数组,其中填充了作为可变参数传递的值。因此,您将创建一个大小为 1 的数组,其中
integer
作为其唯一值。

© www.soinside.com 2019 - 2024. All rights reserved.