Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many elements when initialize hashmap

Tags:

hashmap

scala

When I set immutable hashmap contents on initialization like this:

var result_tags=HashMap[String,Int]()
    result_tags=("video"->0,"game"->0,"news"->0,"ee"->0,"sport"->0,
  "shop"->0,"ju"->0,"story"->0,"pho"->0,"con"->0,"live"->0,"life"->0,"soft"->0,"hire"->0,"car"->0,
  "mm"->0,"mus"->0,"mob"->0,"male"->0,"heal"->0, "sca"->0,"bank"->0,"mail"->0,"cool"->0,"pict"->0, "dl"->0)

It gives me the error:

too many elements for tuple:26,allowed:22

It means the max number of tuples is 22. I know -> is for creating tuples. Is there other ways to initialize hashmap without the limit number of its elements.

like image 748
FancyXun Avatar asked Dec 03 '25 17:12

FancyXun


2 Answers

What you're actually doing there is initializing a giant Tuple type and trying to assign it to the result_tags variable which is of type HashMap, which wouldn't work even if the tuple size wouldn't exceed maximum size.

So the error you get regarding tuples is not referring to the -> syntax that you use, but to the number of elements inside the (...) list. You would get the same error even if you wrote it like this:

(("video", 0), ("game", 0), ..., ("dl", 0))

Second, in your case you should do:

var result_tags = HashMap("video" -> 0, "game" -> 0, ..., "dl" -> 0)

(notice that I omitted the type info because Scala infers the type for you.)

The (a1, a2, ..., aN) syntax is an entirely different thing in Scala, since it initializes a tuple type. Every such declaration is converted into a TupleN type, where the maximum size is 22. So the Scala library actually has 22 distinct Tuple classes from Tuple1 to Tuple22.

Third, your style could use some corrections

  • You should prefer the immutable version of map which is scala.collection.Map
  • You should prefer immutable variables, which means val instead of var
  • And less important, but variable names are preferred to be camelCased, so that would be resultTags
like image 162
Ori Popowski Avatar answered Dec 06 '25 10:12

Ori Popowski


Just

var result_tags = Map("video"->0,"game"->0,"news"->0,"ee"->0,"sport"->0,
  "shop"->0,"ju"->0,"story"->0,"pho"->0,"con"->0,"live"->0,"life"->0,"soft"->0,"hire"->0,"car"->0,
  "mm"->0,"mus"->0,"mob"->0,"male"->0,"heal"->0, "sca"->0,"bank"->0,"mail"->0,"cool"->0,"pict"->0, "dl"->0)
like image 27
ars Avatar answered Dec 06 '25 08:12

ars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!