【发布时间】:2011-12-04 17:04:53
【问题描述】:
我想创建对象的哈希图并使用二维键:
public HashMap<ConversationKey, ConversationItem> ConversationMap = new HashMap<ConversationKey, ConversationItem>();
对话键在哪里:
public class ConversationKey {
private String Left;
private String Right;
}
但我不完全理解我需要什么过度方法,另一篇文章说我需要 hashcode() 和 equals() 但 hashcode() 不可用,自动添加未实现的方法只是添加 compareTo()
谁能帮我制作一个二维键对象,通过提供两个字符串值作为键来从哈希图中检索项目?
这是我目前所拥有的:
public class ConversationKey implements Comparable<ConversationKey> {
private String Left;
private String Right;
public ConversationKey(String left, String right) {
Left = left;
Right = right;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ConversationKey) {
return Left.equals(((ConversationKey)obj).Left) &&
Right.equals(((ConversationKey)obj).Right);
}
return false;
}
@Override
public int compareTo(ConversationKey another) {
if (Left.equals(another.Left) && Right.equals(another.Right)) {
return 0;
}
return -1;
}
}
最终实现是:
ConversationKey ck = new ConversationKey("jack", "jane");
ConversationItem Conversation1 = ConversationMap.get(ck);
【问题讨论】: