java - 将 <Object, Object> 放入 TreeMap 时出错

标签 java dictionary treemap

我有以下两个类,它们定义了我想放入 TreeMap 中的对象:

class GeneKey {

    String PN;
    int PW;

    // Generator makes unique TreeMap key.
    GeneKey(String a, int b){
        this.PN = a;
        this.PW = b;
    }
}   

然后是第二个对象:

class GeneValue {

    String info;
    String date;

    // Generator makes TreeMap value
    GeneValue(String a, String b){
        this.info = a;
        this.date = b;
    }
}   

然后我想制作一个 TreeMap:

import java.util.TreeMap;

// In main ...
TreeMap<GeneKey, GeneValue> samples = new TreeMap<GeneKey, GeneValue>();  

String a = "test";
int b = 100;

String c = "test again";
String d = "test yet again";

// Try to put these objects into the tree map.
samples.put(new GeneKey(a, b) ,new GeneValue(c,d))

但是我得到以下错误:

Exception in thread "main" java.lang.ClassCastException: GeneKey cannot be cast to java.lang.Comparable

我想知道为什么我无法建立一个键:值是 GeneKey:GeneValue 的 TreeMap,即使我在初始化 TreeMap 时指定了这些对象。如何初始化 map 以便 .put() 这两个对象。

谢谢

最佳答案

TreeMap 是一个有序容器:当您请求它的键或条目时,您会按特定顺序获取它们。

顺序取决于您提供的 key 。为了让容器对键进行排序,每个键都需要实现Comparable接口(interface):

class GeneKey implements Comparable<GeneKey> {

    String PN;
    int PW;

    // Generator makes unique TreeMap key.
    GeneKey(String a, int b){
        this.PN = a;
        this.PW = b;
    }
    public int compareTo(GenKey other) {
        int res = PN.compareTo(other.PN);
        return (res != 0) ? res : Integer.compare(PW, other.PW);
    }
}

这不是基于散列的容器的要求,因为一切都继承自 Object,它提供 hashCodeequals

关于java - 将 <Object, Object> 放入 TreeMap 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182413/

相关文章:

javascript - d3 可缩放 TreeMap - 每个父宽度的动态文本宽度

java - Swift 的 CharacterSet.decimalDigits 和 unicodeScalars 在 Kotlin 中的等价物是什么

java - Oracle xdb-xmlparser 源代码

data-structures - 有没有提供关联数组功能的 go 库?

kendo-ui - 剑道 UI TreeMap json 绑定(bind)

performance - 最有效地在 TreeMap 中找到第 N 个键

java - 避免使用instanceof模式

java - 线程间通信程序

Java 2D 游戏图 block 渲染优化

c++ - 如何在 C++ 中的日文字符串中查找空格?