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 编程方面的解释。