Using Java PriorityQueue in Matlab

蹲街弑〆低调 提交于 2020-01-03 18:14:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!