Reputation: 33
What are the main differences in using an Array/list or a set. What would be a reason to use one over the other? I have looked at the documentation and it seems that they both have many common methods.
I all ready know that Lists are immutable and how sets are both immutable and mutable.
val Stuff = Array(1,2,3,4)
val Apple = Set(1,2,3,4)
Stuff.map(x => x*2)
Apple.map(x => x*2)
Upvotes: 3
Views: 6213
Reputation: 1265
The main difference in terms of functionality is the fact that Set
s cannot contain duplicate elements.
Adding to collection where the element already exists yields no effect.
Upvotes: 4
Reputation: 52681
A Set
is unordered and can't have duplicate items.
scala> Set(1,2,3,1,2,3) == Set(3,2,1)
res2: Boolean = true
Sequences (Array
, List
, Vector
, etc) are ordered and can have repeated elements.
To use your example (which, incidentally, doesn't compile...):
val stuff = Array(1, 2, 3, 4)
val apple = Set(1, 2, 3, 4)
stuff.map(x => x % 3) // Array(1, 2, 0, 1)
apple.map(x => x % 3) // Set(1, 2, 0)
Upvotes: 12