我想做一些类似的事情
object.set(lineIndex, wordIndex, value);
这个用于检索
value=object.get(lineIndex,wordIndex);
但是ArrayList和HashMap不支持2个键值
任何想法!!
谢谢
最佳答案
创建一个类来存储您要使用的两个键,并将其用作 Map
中的键。它会有一点开销,但应该比嵌套的 HashMap 使用更少的内存。
示例:
class IndexKey{
public final int lineIndex;
public final int wordIndex;
public IndexKey(int lineIndex, int keyIndex){
this.lineIndex = lineIndex;
this.wordIndex = wordIndex;
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + lineIndex;
hash = 97 * hash + wordIndex;
return hash
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IndexKey other = (IndexKey) obj;
if (this.lineIndex != other.lineIndex) {
return false;
}
if (this.wordIndex != other.wordIndex) {
return false;
}
return true;
}
}
Map<IndexKey, Object> map = new HashMap<>();
object.set(new IndexKey(lineIndex, keyIndex), value);
value=object.get(new IndexKey(lineIndex, wordIndex));
关于java - 如何使用 2 个键在 HashMap 或 ArrayList 上获取或设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655930/