Why does my PriorityBlockingQueue in Java not sort properly?

喜夏-厌秋 提交于 2019-12-20 04:19:50

问题


For some reason when I add to the priority queue, it doesn't sort my strings entirely alphabetically and I can't see why.

This is the code which adds to the PriorityBlockingQueue:

String toAdd = String.format("%s/%s", directory, s);
outputData.add(toAdd);

But I get not entirely sorted output (only first few lines but you can see it's not sorted):

../StartingTree/files/abknl/apfmpohgyh/a.class
../StartingTree/files/abknl/apfmpohgyh/a.java
../StartingTree/files/abknl/aqybc/aeph.java
../StartingTree/files/abknl/apfmpohgyh/bnjuxxdi.class
../StartingTree/files/abknl/bbxudleuf/jlffhq/y/xwjj/dyetqhsch/bpg.class
../StartingTree/files/abknl/bbxudleuf/mxb/fe/ndmg/axapxuco.html
../StartingTree/files/abknl/aqybc/atyuojdu.txt

And this is the real (first part) of sorted output from the expected-output file:

../StartingTree/files/abknl/apfmpohgyh/a.class
../StartingTree/files/abknl/apfmpohgyh/a.java
../StartingTree/files/abknl/apfmpohgyh/bnjuxxdi.class
../StartingTree/files/abknl/apfmpohgyh/bnjuxxdi.java
../StartingTree/files/abknl/apfmpohgyh/bsqsq.class
../StartingTree/files/abknl/apfmpohgyh/bsqsq.java
../StartingTree/files/abknl/apfmpohgyh/ds.class
../StartingTree/files/abknl/apfmpohgyh/ds.java

回答1:


I suspect you are trying to iterate the PriorityBlockingQueue and print the elements.

Note that a Priority Queue data structure (AKA heap) does not guarantee ordering - it guarantees that the head is minimal, but no order guarantee on any of the following nodes.

If you want your data maintained sorted - I suggest using something like ConcurrentSkipListSet (Note however it is a set - thus it does not allow duplicate entrees), or maintaining a sorted List.

If you want to get the sorted elements using a PriorityBlockingQueue - you should iteratively delete the head and output the new head - until the priority queue is exhausted. It will guarantee an ordered output.



来源:https://stackoverflow.com/questions/13370431/why-does-my-priorityblockingqueue-in-java-not-sort-properly

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