Scala HashSet java.lang.NegativeArraySizeException

时间:2018-11-16 20:45:49

标签: scala hashset

以下代码在插入483180000值后引发异常。这是预期的吗?有什么方法可以将超过十亿个值添加到Scala中的可变HashSet中。在Scala 2.11和2.12版本中尝试了此代码。两种版本都会引发相同的异常。

import scala.collection.mutable.HashSet

object TestApp extends App {
    val hs = HashSet[Int]()
    for (i <- 1 to Int.MaxValue) {
        hs += i
    }
}

java.lang.NegativeArraySizeException
        at scala.collection.mutable.FlatHashTable.growTable(FlatHashTable.scala:218)
        at scala.collection.mutable.FlatHashTable.addEntry(FlatHashTable.scala:160)
        at scala.collection.mutable.FlatHashTable.addEntry$(FlatHashTable.scala:148)
        at scala.collection.mutable.HashSet.addEntry(HashSet.scala:39)
        at scala.collection.mutable.FlatHashTable.addElem(FlatHashTable.scala:140)
        at scala.collection.mutable.FlatHashTable.addElem$(FlatHashTable.scala:139)
        at scala.collection.mutable.HashSet.addElem(HashSet.scala:39)
        at scala.collection.mutable.HashSet.$plus$eq(HashSet.scala:58)
        at alice.grid.collection.TestApp$.$anonfun$new$2(TestApp.scala:12)
        at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:155)
        at alice.grid.collection.TestApp$.delayedEndpoint$alice$grid$collection$TestApp$1(TestApp.scala:11)
        at alice.grid.collection.TestApp$delayedInit$body.apply(TestApp.scala:5)
        at scala.Function0.apply$mcV$sp(Function0.scala:34)
        at scala.Function0.apply$mcV$sp$(Function0.scala:34)
        at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
        at scala.App.$anonfun$main$1$adapted(App.scala:76)
        at scala.collection.immutable.List.foreach(List.scala:388)
        at scala.App.main(App.scala:76)
        at scala.App.main$(App.scala:74)
        at alice.grid.collection.TestApp$.main(TestApp.scala:5)
        at alice.grid.collection.TestApp.main(TestApp.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)

1 个答案:

答案 0 :(得分:3)

不,没有办法,如何添加那么多项目。如果您在(FlatHashTable.scala:218处查看源代码,则会发现:

table = new Array[AnyRef](table.length * 2)

lenth是一个整数。在某些时候,将其乘以2将导致溢出,并且结果为负数。 Java不允许创建大小为负数的数组。

这仅仅是HashSet的实现所施加的限制。