Sort ArrayBuffer[A] in scala?
I have an array in Scala with the class ArrayBuffer[Actor]
, where Actor
is a class that implements the Ordered[Actor]
trait. How do I sort this array without coding it manually?
I know there is an object called Sorting
, but it doesnt seem to work since ArrayBuffer
doesn't implement/extend the righ开发者_运维问答t classes.
How do I sort ArrayBuffer[A]
type arrays?
If you are using Scala 2.8, you could use the sortWith
method of the ArrayBuffer[T]
class, which is inherited from the SeqLike
trait.
The following code snippet sorts an ArrayBuffer[T]
object in ascending order:
def ascendingSort[T <% Ordered[T]](xs: ArrayBuffer[T]) = xs.sortWith(_ < _)
Note that this does not mutate the actual ArrayBuffer
, but creates a new one with the elements in the right order.
If you are using Scala 2.7, you could use the stableSort
method of the Sorting
object. This takes the elements of the ArrayBuffer
and produces an array of elements sorted in the right order (given by a closure as an argument, ascending as a default).
For example:
val a = new scala.collection.mutable.ArrayBuffer[Int]()
a += 5
a += 2
a += 3
scala.util.Sorting.stableSort(a)
The important question is what do you want to do with the ArrayBuffer
. Usually, a Buffer
is used internally in different algorithms in order to increase the performance of intermediate results. If you are using it for that, have a look at the ways of sorting the collection you want to return at the end of your algorithm. The Sorting
object already provides a way of transforming an ArrayBuffer
into a sorted Array
.
From the scaladoc of the Buffer
class:
Buffers are used to create sequences of elements incrementally
As you are using it with Actor
s, it might be used for some kind of actor queue - in which case, you might want to have a look at the Queue
collection.
Hope it helps,
-- Flaviu Cipcigan
Btw, the Actor class here is my own class used for "Actors" in a world created using my new game engine for scala ("Awesome Game Engine for Scala ~ AGES"), so it has nothing to do with the concurrency actor class. Also, implementations of lists in scala are a jungle, everything is either deprecated or implemented in a lot of different ways...ArrayBuffer works for my need (my need being a variable size array for containing actors).
Hope this clarifies :)
精彩评论