This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Which Map-Class?

2 replies
Kai Meder
Joined: 2009-04-29,
User offline. Last seen 42 years 45 weeks ago.

Hello

which mutable class is appropriate for a Map Int -> List[Model] ?
I want to add Model-Instances to the List of Models, determined by an
Integer-Key.

Thanks,
Kai

Ken Scambler
Joined: 2009-11-07,
User offline. Last seen 42 years 45 weeks ago.
Re: Which Map-Class?

Hi Kai,
I'd strongly recommend you consider an immutable Map as a first resort. It
still allows you to add new data, it just returns a new instance instead.
For instance, these two calls have (essentially) the same effect for your
program:

import scala.collections._

val map: mutable.Map[Int, List[Model]] = mutable.Map()
map += (5 -> List(m1, m2)) // calls the += method on the mutable map

// OR....
var map: Map[Int, List[Model]] = Map() // uses the immutable map by default
map += (5 -> List(m1, m2)) // syntax sugar for map = map + (5 -> List(m1,
m2))

The difference is that the first mutates your map, whose state might be
shared elsewhere; the second replaces your map instance with a new map,
whose state is fixed and cannot be corrupted.

To directly answer your question, there are HashMap, HashTable and
LinkedHashMap implementations in the scala.collections.mutable package,
although you should rarely need them explicitly; use Map() as a first
resort, and s.c.m.Map if you really need a mutable one.

I'd also recommend you do some background reading, such as:
http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bo...

and also the ScalaDocs with attached source code:
http://www.scala-lang.org/docu/files/api/index.html

Hope this helps!

Ken

Kai Meder-2 wrote:
>
> Hello
>
> which mutable class is appropriate for a Map Int -> List[Model] ?
> I want to add Model-Instances to the List of Models, determined by an
> Integer-Key.
>
> Thanks,
> Kai
>
>

ounos
Joined: 2008-12-29,
User offline. Last seen 3 years 44 weeks ago.
Re: Which Map-Class?

I would very like to say "use a multimap" but it's not to clear, since
as it has been already discussed, current "MultiMap" has Set[A]
values.

Personally I would use scala.collection.JavaConversions and wrap a
google collections multimap, or use the latter directly. Lets hope
this situation gets better.

(all this assuming that your Ints are not in the range [0...N] for some small N)

Dimitris

2009/11/30 Kai Meder :
> Hello
>
> which mutable class is appropriate for a Map Int -> List[Model] ?
> I want to add Model-Instances to the List of Models, determined by an
> Integer-Key.
>
> Thanks,
> Kai
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland