When transferring elements from a PriorityQueue
to an ArrayList
I noticed List.add
and List.addAll
behave differently. But I'm not sure why.
Example code:
public static void main(String[] args) {
PriorityQueue<String> heap = new PriorityQueue<>(Comparator.reverseOrder());
heap.add("a");
heap.add("aa");
heap.add("aaa");
ArrayList<String> listAddAll = new ArrayList<>();
listAddAll.addAll(heap);
System.out.println(listAddAll);
ArrayList<String> listAdd = new ArrayList<>();
while (!heap.isEmpty()){
listAdd.add(heap.remove());
}
System.out.println(listAdd);
}
The listAddAll
contains [aaa, a, aa]
while listAdd
contains [aaa, aa, a]
. I'd expect both to be the latter as that is the order specified by the comparator.