【发布时间】:2012-03-05 21:32:02
【问题描述】:
我正在使用 HashMap 数据结构来存储 SqMatrix(方阵),其中键是 MatrixIndex 类型(包含行和列),值是整数类型。
但是当我得到 false 作为“if (mat.containsKey(key))”的输出时,尽管 HashMap 中有相应的键。
主要代码:
public static void main(String[] args) {
Random generator = new Random();
int val = 0;
Types.MatrixIndex key, key1;
int matSz = (int) Math.floor(Math.sqrt(10));
Types.SqMatrix mat = new Types().new SqMatrix(matSz); //matSz*matSz elements
//HashMap<Types.MatrixIndex,Integer> hMap= new HashMap<Types.MatrixIndex,Integer>(10);
for (int r=0; r<matSz; r++) {
for (int c=0; c<matSz; c++) {
if (r<c) {
val = generator.nextInt(2) > 0? -1 : val;
key =(new Types()).new MatrixIndex(r, c);
key1 = (new Types()).new MatrixIndex(c, r);
mat.put(key, val);
mat.put(key1, val);
generator.setSeed(System.currentTimeMillis());
}
}
}
for (int r=0; r<matSz; r++) {
val = 0;
for (int c=0; c<matSz; c++) {
if (r!=c) {
key = (new Types()).new MatrixIndex(r, c);
if (mat.containsKey(key)) {
val = val + mat.get(key);
}
}
}
key1 = (new Types()).new MatrixIndex(r, r);
mat.put(key1, val);
}
有人知道为什么 containsKey 虽然存在于 HashMap 中却返回 false 吗?
提前致谢,
索姆纳特
【问题讨论】:
-
对stackoverflow.com/questions/1104030/… 的接受 答案可能会有所帮助,因为我怀疑您还没有为
MatrixIndex类实现equals()和hashCode() -
我没有任何链接可以接受答案。任何线索如何接受任何回复?
标签: java