Java 放置时出错<;对象,对象>;进入树梢
我有以下两个类,它们定义了我想放入树映射的对象:Java 放置时出错<;对象,对象>;进入树梢,java,dictionary,treemap,Java,Dictionary,Treemap,我有以下两个类,它们定义了我想放入树映射的对象: class GeneKey { String PN; int PW; // Generator makes unique TreeMap key. GeneKey(String a, int b){ this.PN = a; this.PW = b; } } import java.util.TreeMap; // In main ... TreeMap<
class GeneKey {
String PN;
int PW;
// Generator makes unique TreeMap key.
GeneKey(String a, int b){
this.PN = a;
this.PW = b;
}
}
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))
然后是第二个对象:
class GeneValue {
String info;
String date;
// Generator makes TreeMap value
GeneValue(String a, String b){
this.info = a;
this.date = b;
}
}
然后我想做一个树形图:
class GeneKey {
String PN;
int PW;
// Generator makes unique TreeMap key.
GeneKey(String a, int b){
this.PN = a;
this.PW = b;
}
}
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))
我想知道为什么我不能用key:value的GeneKey:GeneValue建立树映射,即使我在初始化树映射时指定了这些对象。如何初始化映射以便.put()这两个对象
谢谢
TreeMap
是一个有序的容器:当您请求它的密钥或条目时,您会按照特定的顺序获得它们
订单取决于您提供的钥匙。为了让容器订购密钥,每个密钥都需要实现compariable
接口:
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);
}
}
类GeneKey实现了可比较的{
字符串PN;
int PW;
//生成器生成唯一的树映射键。
基因键(字符串a,整数b){
这个.PN=a;
这个.PW=b;
}
公共整数比较(GenKey其他){
int res=PN.compareTo(其他PN);
返回(res!=0)?res:Integer.compare(PW,other.PW);
}
}
这不是基于散列的容器的要求,因为所有内容都继承自
对象
,该对象提供散列代码
,并且等于
在GeneKey
中实现可比
?这几乎是一个重复。