English 中文(简体)
How is the Java priority Queue supposed to work? [duplicate]
原标题:

Short story, I m implementing a graph and now I m working on the Kruskal, I need a priority queue. My definition of a priority queue is that the element with the smallest key would come first? Is this wrong? Because when I insert the weighted edges(or numbers) in the queue they don t end up sorted.

PriorityQueue<Integer> tja = new PriorityQueue<Integer>(); 
tja.add(55);
tja.add(99); 
tja.add(1); 
tja.add(102);
tja.add(54);
tja.add(51);
System.out.println(tja);

That would print out this; [1, 54, 51, 102, 99, 55]. This is not sorted like I want them to be! And yes I made a comperator that goes into the priority queue that extracts the number from the edge object and compares based on that int. So this should work, or have I just completely misunderstood the entire concept of how this data structure works?

最佳回答

System.out.println is invoking the toString() method, which is using the iterator, which is not guaranteed to respect the natural ordering. From the docs: "The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order."

问题回答

I have no experience with PriorityQueue in Java but it looks like the priority thing is not integrated into iterator() or toString() (which uses iterator()).

If you do:

    while (tja.size()>0)
        System.out.println(tja.remove());

You get the proper results.

Are you familiar with functioning of Binary heaps? If not please go through min heap and max heap structures. PriorityQueue is implemented on heaps. PriorityQueue doesn t sort the items in increasing order, but it does the heap sort on it.

Go through the link: Priority Queue

The output you get is correct.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签