问题
I need a min-heap in Matlab and I'm trying to use Java's PriorityQueue. I'm stuck on how to supply the Comparator. So far I have initialized the PriorityQueue and can add one value-index pair to it:
>> q = java.util.PriorityQueue
q =
[]
>> q.add({1,3})
ans =
1
The problem occurs when I try to add more data:
>> q.add({2,4})
??? Java exception occurred:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
From this post, I see that I need to supply a Comparator function, but I don't know how to do this.
回答1:
Priority queues need to either contain objects that implement Comparable, or you need to pass in a Comparator function at construction time.
There isn't a way currently in MATLAB to either implement Java interfaces with MATLAB code, or supply literal Java code.
So you'd have to follow @nibot's suggestion and make a small .jar file containing a class implementing Comparator.
回答2:
import java.util.*;
q = java.util.PriorityQueue();
for i=1:10
q.add(i);
end
disp(q)
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
来源:https://stackoverflow.com/questions/5454364/using-java-priorityqueue-in-matlab