java - 我们如何在 TreeMap 中使用异构键

标签 java

在执行下面提到的代码时,我得到

Exception in thread "main" java.lang.ClassCastException: com.test.tree.T1 cannot be cast to com.test.tree.T2
    at com.test.tree.TestComparator.compare(TestTreeMap.java:59)
    at java.util.TreeMap.put(TreeMap.java:530)
    at com.test.tree.TestTreeMap.main(TestTreeMap.java:22)

代码:

package com.test.tree;

import java.util.Comparator;
import java.util.TreeMap;

public class TestTreeMap{

    public static void main(String[] args) {

        TreeMap tree=new TreeMap(new TestComparator());
        T1 t1=new T1(10, 20);
        T2 t2=new T2(10,21);
        tree.put(t1, 23);
        tree.put(t2, 24);
    }

}
class T1 {
   int x,y;

    public T1(int x, int y) {
    super();
    this.x = x;
    this.y = y;
}


}
class T2 {
   int x,y;
    public T2(int x,int y) {
        super();
        this.x = x;
        this.y = y;
}

}

class TestComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        System.out.println("hi im called");
        T1 t1=(T1)o1;
        T2 t2=(T2)o2;
        return t1.x-t2.y;
        }

}

最佳答案

您不能假设 compare 将始终接收 T1 实例作为第一个参数,并接收 T2 实例作为第二个参数。它可能会接收两个 T1 实例或两个 T2 实例,或两者的实例,但不是按照您期望的顺序。

在将 o1o2 转换为 T1T2 之前,您必须测试它们的类型。

@Override
public int compare(Object o1, Object o2) {
    if (o1 instanceof T1) {
        if (o2 instanceof T2) {
            T1 t1=(T1)o1;
            T2 t2=(T2)o2;
            return t1.x-t2.y;
        } else {
           ...
        }
    } else {
        ...
    }
}

这是假设您的 TreeMap 的键只能是 T1T2

关于java - 我们如何在 TreeMap 中使用异构键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34591349/

相关文章:

java - 基于现有 WSDL 生成 Java Webservice 的工具

java - Android - 关于应用程序管理器中的框?

java - 自定义 AlertDialog 未在 runonuithread 方法中显示

java - 来自根路径的 Zuul 路由

java - Spring JPA中调用oracle函数

java - 数学加法代码,尝试在正确答案后结束

java - 加速实体管理器3000条记录的提交

Java 列表列表

java - 为什么第一次调用构造函数花费的时间比其他调用多 10 倍?

java - 调用 quit() 后无法使用 WebDriver FirefoxDriver