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

如何在外部泛型方法中调用类的Comparator?

问题分析与解决方案

错误原因

你遇到的类型冲突本质是泛型类型不匹配:

  • Event.YComparator实现的是Comparator<Event>,它的compare方法仅能接收两个Event类型参数。
  • 但泛型方法Rec中的value和current.value是泛型类型T,编译器无法确定T就是Event,因此报错提示无法将(T, T)传入compare(Event, Event)。

同时你的两个Comparator是Event专属的(依赖Event的x、y字段),天然只能用于Event类型对象的比较。


解决方案

方案1:移除泛型,直接指定类型为Event

如果你的Node类和Rec方法本来就是为处理Event对象设计的,最直接的方式是去掉泛型T,将类型明确为Event:

修改后的Rec方法代码:

Node Rec(Node current, Event value, Event.YComparator comp) {
    if (current == null) {
        size++;
        current = new Node(value);
        return current;
    }

    if (comp.compare(value, current.value) < 0) {
        current.leftChild = Rec(current.leftChild, value, comp);
    } else if(comp.compare(value, current.value) > 0) {
        current.rightChild = Rec(current.rightChild, value, comp);
    } else {
        return current;
    }
    return current;
}

对应的Node类需同步修改value字段类型:

class Node {
    Event value;
    Node leftChild;
    Node rightChild;

    Node(Event value) {
        this.value = value;
    }
}

方案2:约束泛型T为Event,适配现有Comparator

如果需要保留泛型(比如未来可能扩展Event的子类),可以给泛型方法添加类型约束,确保T是Event或其子类,同时将Comparator参数改为Comparator<T>:

修改后的Rec方法定义:

<T extends Event> Node Rec(Node current, T value, Comparator<T> comp) {
    if (current == null) {
        size++;
        current = new Node(value);
        return current;
    }

    if (comp.compare(value, (T) current.value) < 0) {
        current.leftChild = Rec(current.leftChild, value, comp);
    } else if(comp.compare(value, (T) current.value) > 0) {
        current.rightChild = Rec(current.rightChild, value, comp);
    } else {
        return current;
    }
    return current;
}

调用时直接传入Event.YComparator实例即可,因为Event.YComparator是Comparator<Event>,满足<T extends Event>的约束:

Event.YComparator yComp = new Event.YComparator();
// 假设root是Node类型
root = Rec(root, new Event(1,2,true,0), yComp);

方案3:将内部Comparator改为泛型(可选,提升扩展性)

如果希望Comparator能支持Event的子类,可以把内部Comparator改为泛型:

static class YComparator<T extends Event> implements Comparator<T> {
    @Override
    public int compare(T e1, T e2) {
        return (e1.y < e2.y) ? -1 : (e1.y > e2.y) ? 1 : (e1.x < e2.x) ? -1 : 1;
    }
}

搭配方案2的泛型方法,就能更好地支持Event子类的比较逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:07:37