我对PriorityQueue有问题。
public static void main(String[] args) {
sortByBits(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8});
}
public static int[] sortByBits(int[] arr) {
Map<Integer, Integer> m = new HashMap<>();
PriorityQueue<Integer> p = new PriorityQueue<>(Comparator.comparing(m::get));
for (int i = 0; i < arr.length; i++) {
m.put(arr[i], calCount(arr[i]));
p.offer(arr[i]);
}
other codes.......
地图m是0-> 0,1-> 1,2-> 1,3-> 24-> 1,5-> 26-> 27-> 3,8-> 1,我想按PriorityQueue中地图的值进行排序,预期结果是0-1-2-4-8-3-5-6-7或其他,但现在是0-1-2-8-4-5-6-7-3,很明显键7的值是3,最大,应该在末尾...但是现在结尾是3,我不知道不知道为什么。谢谢。
PriorityQueue将按照自然顺序对项目进行排序。由于它们是整数,因此将按升序排序。有关如何排序所需方式的信息,请参见here。