ArrayList自定义类作为HashMap键 [英] ArrayList custom class as HashMap key

查看:156
本文介绍了ArrayList自定义类作为HashMap键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的数据存储在 HashMap< Point [],Double> 中。我使用迭代来分配数据,但是当我在最后检查时,元素的数量仅为1.我已经实现了 hashCode()等于()在自定义类Point中。 hmDistOrd = new HashMap< Point [],Double>();
Point [] keyPts = new Point [2];

for(int i = 0; i< intersectionPts.size(); i ++){
p1 = intersectionPts.get(i);
for(int j = 0; j< intersectionPts.size(); j ++){
p2 = intersectionPts.get(j);
if(!p1.equals(p2)){
keyPts [0] = p1;
keyPts [1] = p2;
d = p1.distance(p2);
hmDistOrd.put(keyPts,d);
}
}
}

任何提示?提前致谢!

解决方案

您不能使用数组作为键,因为数组的默认实现为 hashCode 等于 from Objects ,它并不认为它是元素。为了使它工作,你必须重写 hashCode equals 你可以使用 ArrayList 来代替,因为它实现了 hashCode end 等于比较元素。


I want to store my data in HashMap<Point[], Double>. I used iteration to assign the data, but when I checked at the end, the number of elements is only 1. I have implemented hashCode() and equals() in the custom class Point.

HashMap<Point[], Double> hmDistOrd = new HashMap<Point[], Double>();
Point[] keyPts = new Point[2];

for (int i=0; i<intersectionPts.size(); i++) {
p1 = intersectionPts.get(i);
    for (int j=0; j<intersectionPts.size(); j++) {
        p2 = intersectionPts.get(j);                
        if (!p1.equals(p2)) {
            keyPts[0] = p1;
            keyPts[1] = p2;
            d = p1.distance(p2);
            hmDistOrd.put(keyPts, d);
        }
    }
}

Any hints? Thanks in advance!

解决方案

You can't use array as a key, as array has default implementation of hashCode and equals from Objects and it doesn't consider it's elements.

To make it work you had to override hashCode and equals of array, but you can't do it.

You can use ArrayList instead, as it implements hashCode end equals comparing elements.

这篇关于ArrayList自定义类作为HashMap键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆