You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中实现以数组第0位为基准的int[]类型大顶堆的异常处理

解决PriorityQueue<int[]>大顶堆的ClassCastException问题

异常原因

ClassCastException的根源是int[]数组并未实现Comparable接口,而Collections.reverseOrder()默认要求队列元素必须是Comparable类型以执行默认排序逻辑,因此直接使用会触发类型转换异常。

解决方案:自定义Comparator

要实现以int[]第0位元素为基准的大顶堆,需要手动指定排序规则,通过自定义Comparator定义数组的比较逻辑:

方式1:Java 8+ Lambda表达式(简洁写法)

// 按int[]第0位元素降序排列,构建大顶堆
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0]));

说明:使用Integer.compare(b[0], a[0])而非直接b[0]-a[0],是为了避免int数值溢出导致的排序错误。

方式2:匿名内部类(兼容Java 8之前版本)

PriorityQueue<int[]> maxHeap = new PriorityQueue<>(new Comparator<int[]>() {
    @Override
    public int compare(int[] a, int[] b) {
        // 降序排序:b的第0位大于a则返回正,确保大的元素排在堆顶
        return Integer.compare(b[0], a[0]);
    }
});

验证示例

import java.util.Arrays;
import java.util.PriorityQueue;

public class MaxHeapTest {
    public static void main(String[] args) {
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0]));
        
        maxHeap.add(new int[]{3, 10});
        maxHeap.add(new int[]{1, 20});
        maxHeap.add(new int[]{5, 5});
        
        // 堆顶应为第0位最大的[5,5]
        System.out.println(Arrays.toString(maxHeap.peek())); // 输出 [5, 5]
        
        maxHeap.poll(); // 弹出堆顶元素
        // 新堆顶为[3,10]
        System.out.println(Arrays.toString(maxHeap.peek())); // 输出 [3, 10]
    }
}

内容的提问来源于stack exchange,提问作者Nitin Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:35:23