Skip to content

Instantly share code, notes, and snippets.

@chids
Created September 12, 2011 16:46
Show Gist options
  • Save chids/1211738 to your computer and use it in GitHub Desktop.
Save chids/1211738 to your computer and use it in GitHub Desktop.
PriorityQueue sorting weirdness
System.err.println(new PriorityQueue<Integer>(Arrays.asList(3, 1, 2)));
// Prints: [1, 3, 2]
System.err.println(new TreeSet<Integer>(Arrays.asList(3, 1, 2)));
// Prints: [1, 2, 3]
/*
This is due to PriorityQueue's Iterator. From the javadoc:
"...Iterator provided in method iterator() is not guaranteed to
traverse the elements of the priority queue in any particular order...".
PriorityQueue.toString() is in reality AbstractCollection.toString()
which uses the iterator of the subclass to print the elements.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment