Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default capacity/load factor of scala mutable.HashMap

I am currently using scala 2.9.1. I create a mutable.HashMap using :

> val m = mutable.HashMap.empty[Int, Int]

I am kind of new to scala. In java, I was able to specify the capacity and load factor in the constructor of a HashMap. I am not able to find any way to do the same in scala.

Thanks in Advance

like image 821
arun_suresh Avatar asked Apr 08 '12 14:04

arun_suresh


People also ask

Can we change load factor of HashMap?

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75). Constructs an empty HashMap with the specified initial capacity and load factor. As @Xoce mentioned, you can't change loadFactor later, I do agree with him on this. Use it while creating the hashmap.

How do I set initial capacity of HashMap?

Initial Capacity of HashMap The initial capacity of the HashMap is the number of buckets in the hash table. It creates when we create the object of HashMap class. The initial capacity of the HashMap is 24, i.e., 16. The capacity of the HashMap is doubled each time it reaches the threshold.

What is the default value of load factor in HashMap?

The default load factor is 75% of the capacity. The threshold of a HashMap is approximately the product of current capacity and load factor.

How load factor is calculated in HashMap?

Default initial capacity of the HashMap takes is 16 and load factor is 0.75f (i.e 75% of current map size). The load factor represents at what level the HashMap capacity should be doubled. For example product of capacity and load factor as 16 * 0.75 = 12 .


1 Answers

According to the API, this does not seem to be possible. One explanation is that mutable collections are strongly discouraged, and immutable collections don't need the default capacity information since the number of items must be known at the time of construction.

However, note that Scala will implicitly use default capacity information if you construct a collection (including mutable and immutable HashMap) via the many available collection methods. For example, if you call map on a HashMap, it will use map defined on TraversableLike (reproduced below), and you can see that it provides a "size hint" to the builder that provides that capacity information.

def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  val b = bf(repr)
  b.sizeHint(this)
  for (x <- this) b += f(x)
  b.result
}
like image 197
dhg Avatar answered Oct 05 '22 18:10

dhg