[英]Error when putting <Object, Object> into TreeMap
I have the following two classes which define objects I would like to put into a TreeMap: 我有以下两个类来定义我想要放入TreeMap的对象:
class GeneKey {
String PN;
int PW;
// Generator makes unique TreeMap key.
GeneKey(String a, int b){
this.PN = a;
this.PW = b;
}
}
Then a second object: 然后是第二个对象:
class GeneValue {
String info;
String date;
// Generator makes TreeMap value
GeneValue(String a, String b){
this.info = a;
this.date = b;
}
}
I would like to then make a TreeMap: 我想制作一个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))
But I get the following error: 但是我收到以下错误:
Exception in thread "main" java.lang.ClassCastException: GeneKey cannot be cast to java.lang.Comparable
I would like to know why I am not able to establish a TreeMap with key:value of GeneKey:GeneValue even though I specified those objects when initializing my TreeMap. 我想知道为什么我无法使用key:GeneKey:GeneValue的值建立TreeMap,即使我在初始化TreeMap时指定了这些对象。 How to I initialize the map in order to .put() these two objects.
如何初始化地图以便.put()这两个对象。
Thank you 谢谢
TreeMap
is an ordered container: when you request its keys or its entries, you get them in a certain order. TreeMap
是一个有序容器:当您请求其键或其条目时,您可以按特定顺序获取它们。
The order depends on the key that you supply. 订单取决于您提供的密钥。 In order for the container to order the keys, each key needs to implement
Comparable
interface: 为了使容器能够对密钥进行排序,每个密钥都需要实现
Comparable
接口:
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);
}
}
This is not a requirement for hash-based container, because everything inherits from Object
, which supplies hashCode
and equals
. 这不是基于散列的容器的要求,因为所有内容都继承自
Object
,后者提供hashCode
和equals
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.