Ken
Ken

Reputation: 1558

Different Representations of Scala HashMap

I've been playing around with the Scala HashMap and I've noticed two different representations of the HashMap. I was wondering if somebody could explain the difference of:

Map(123 -> 1)

and

{123=1}

Thanks!

Upvotes: 0

Views: 158

Answers (2)

Jesper
Jesper

Reputation: 206776

-> is a method that creates tuples. By itself it doesn't directly have anything to do with maps. So for example 123 -> 1 returns a tuple (123, 1). You can try this in the REPL:

scala> 123 -> 1
res1: (Int, Int) = (123,1)

You can create a map by supplying tuples to object Map's apply method, which is what you are doing when you do this:

val m = Map(123 -> 1, 456 -> 2)

is the same as

val m = Map.apply(123 -> 1, 456 -> 2)

is the same as

val m = Map.apply((123, 1), (456, 2))

which creates a Map with two entries, one with key 123 and value 1, the other one with key 456 and value 2.

Upvotes: 2

dhg
dhg

Reputation: 52681

Where have you seen {123=1}? It's not a standard representation in Scala, but it is the way Java defines toString for its Maps.

val sm = Map(1->1, 2->2) // Map(1 -> 1, 2 -> 2)

val jm = new java.util.HashMap[Int,Int]()
jm.put(1,1)
jm.put(2,2)
jm   
// java.util.HashMap[Int,Int] = {1=1, 2=2}

Upvotes: 5

Related Questions