scala-PriorityQueue-ordering-explain
at my previous code, i used PriorityQueue
to solve this issue. I am not that faimiliar with scala syntax, so it takes me some time to figure out how th customized the comparator.
for this part of code:
1 | val pq = mutable.PriorityQueue[(String, Int)]()(Ordering.by { |
you can see for PriorityQueue
in scala, it uses Ordering
, I am not sure of there is Comparator
in scala or not,but the Ordering
code looks more concise to me.
but you can still define a Comprator -like
Ordering, such as this
1 | scala> import scala.collection.mutable.PriorityQueue |
you can see, the diff
is a Comparator
also, you could define the Ordering
- implicitly
, such as this:
1 | implicit val MyOrdering: Ordering[(Int, (Int, Int), (Int, Int))] = |
If you define or import the implicit in a function, than it’s everything until the end of the function. If you define it in a class, than it’s everywhere whitin this class. the queue
would implicitly ordered.
and finally, I met a small problem for inserting an element to priority queue.
what wrong with this pq += (s,t)
? isn’t (s,t)
a tuple ?
take a look at this pic below
for +=
, it would also add multiple elements.
so (s,t)
is regarded as 2 element, instead of a tuple
solution:
pq += (s->t)
, you could create a tuple with ‘->’. see linkpq +=((s,t))
pq.enque((s,t))
pq.enque(s->t)