优先级队列的问题
我试图在代码中使用优先级队列,由于某种原因,当我删除对象时,它们不按顺序排列。你知道我做错了什么吗? 这是我的代码:
构造函数:
recordedsong = new PriorityQueue<recordedNote>(50, new Comparator<recordedNote>()
{
public int compare(recordedNote n1, recordedNote n2)
{
long l = n1.rt()-n2.rt();
int i = (int)l;
return i;
}
});
其中每个记录的注释都有一个长值,该值由 rt() 方法返回。
但是当我调用
while (!Song.isEmpty())
{
recordedNote temp = (recordedNote)Song.remove();
并为每个数字打印 temp.rt() 时,所有数字都乱序了。不仅仅是倒序,而是到处都是,比如 1103, 0, 500, 0, 220 之类的顺序。
你能看看我的构造器有什么问题吗?
谢谢!
I'm trying to use a priority queue in my code, and for some reason when I remove the objects, they aren't in order. Do you know what i"m doing wrong?
Here's my code:
the contructor:
recordedsong = new PriorityQueue<recordedNote>(50, new Comparator<recordedNote>()
{
public int compare(recordedNote n1, recordedNote n2)
{
long l = n1.rt()-n2.rt();
int i = (int)l;
return i;
}
});
where each recordedNotehas a long value that is returned my the method rt().
But when I call
while (!Song.isEmpty())
{
recordedNote temp = (recordedNote)Song.remove();
and then print temp.rt() for each one, all the numbers are out of order. And not just like reverse order, but all over the place, like 1103, 0, 500, 0, 220 orders like that.
Can you see if there's anything wrong with my contructor?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
remove 应该可以工作,事实上,它在我创建的一个小示例程序中确实工作得很好,该示例程序是为了帮助回答这个问题:
所以这就引出了一个问题,为什么它不适合你?我自己,我在您的问题中没有看到足够的连贯代码来回答这个问题。我们不确定 Song 是什么,因为我没有看到它被声明为类或变量,而且我也没有看到您在哪里使用 PriorityQueue 变量,recordedsong,在任何地方。所以我建议你做和我一样的事情:创建一个小的可编译的可运行程序,我们可以运行和修改它并演示你的问题,一个 http ://sscce.org
remove should work, and in fact it does work fine in a small example program that I created to help answer this question:
So this begs the question, why isn't it working for you? Myself, I don't see enough coherent code in your question to be able to answer this. We're not sure what is Song as I don't see this declared as a class or a variable, and I also don't see where you're using your PriorityQueue variable, recordedsong, anywhere. So I suggest you do the same thing as I: create a small compilable runnable program that we can run and modify and that demonstrates your problem, an http://sscce.org
我猜我有可能得到0。因此修改compare方法,使其返回正值而不是结果。
I guess there is a possibility for i getting 0. So modify compare method so that it returns a positive value rather than the result.
阅读 PriorityQueue 的 API 文档,它指出下列:
我的猜测是
remove()
也没有义务遵循自然顺序。Reading the API docs for PriorityQueue, it states the following:
My guess is that
remove()
is not obligated to follow the natural ordering, either.