问题
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