1

Trying to create a priority queue with string length as the sorting factor, but the comparator doesn't seem to work. If I use the same operator say on a SortedSet, this works good.

the below code prints: [z, CD, ZHE21, CDE2312, ABC1]

whereas I was expecting: [z, CD, ABC1,ZHE21, CDE2312]

What am I missing?

PriorityQueue<String> queue = new PriorityQueue<String>(100, new Comparator<String>() {
        public int compare(String a, String b) {
            return Integer.compare(a.length(), b.length());
        }
    });

    queue.add("CDE2312");
    queue.add("ABC1");
    queue.add("ZHE21");
    queue.add("CD");
    queue.add("z");

    System.out.println(queue);
  • 1
    From the Javadoc: The Iterator provided in method iterator() and the Spliterator provided in method spliterator()are not guaranteed to traverse the elements ofthe priority queue in any particular order. – Johannes Kuhn Feb 09 '20 at 04:14
  • 2
    If you repeatedly `poll()` the queue, then you will get the elements in the right order. – Johannes Kuhn Feb 09 '20 at 04:15
  • 1
    More importantly, if you simply search on "Java PriorityQueue not working", you'll see that this same question is asked over and over again, and the answers are almost always the same. Best to do this sort of search first before asking. – Hovercraft Full Of Eels Feb 09 '20 at 04:49

0 Answers0