ArrayList自定义类作为HashMap键
我想将数据存储在 HashMap
中。我使用迭代来分配数据,但是当我最后检查时,元素的数量只有1。我在自定义类点。
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);
}
}
}
有什么提示吗?提前致谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能使用数组作为键,因为数组具有来自
Objects
的hashCode
和equals
的默认实现,并且它不考虑它的元素。为了使它工作,你必须重写数组的
hashCode
和equals
,但你不能这样做。您可以使用 ArrayList 来代替,因为它实现了比较元素的 hashCode end 。
You can't use array as a key, as array has default implementation of
hashCode
andequals
fromObjects
and it doesn't consider it's elements.To make it work you had to override
hashCode
andequals
of array, but you can't do it.You can use
ArrayList
instead, as it implementshashCode
endequals
comparing elements.您在每次迭代时将相同的数组实例 keyPts 存储到 HashMap 中(并覆盖其内容)。
You are storing the same array instance, keyPts, into the HashMap on every iteration (and overwriting its contents as well).
正如吉姆在他的(已删除的)答案中所说,您在地图中多次放置相同的关键对象,这将导致替换以前的值。
但是为每个元素放置一个新数组也不会更好 - 那么您将拥有更多键值对,但如果不这样做,您将无法通过
get
方法访问它们拥有正确的数组对象(然后您也可以获得该值),因为数组没有实现.equals
和hashCode
。提出解决方案:您可以使用
List
作为关键类型,并为每对关键点使用一个新列表。确保将列表作为键放入地图后不会修改该列表。 (您可以通过 Collections.unmodifyingList 包装它以确保这一点。)另一种选择是一些自定义的点对类(具有自己的 hashCode 和 equals 实现)。
As Jim said in his (deleted) answer, you are putting the same key object several times in the map, which will result in replacing the previous value.
But putting a new array for each element will not be better, either - then you will have more key-value-pairs, but you can't access them via the
get
method, if you don't have the right array object (and then you could have the value, too), as arrays do not implement.equals
andhashCode
.To propose a solution: You could use an
List<Point>
as your key type, and use a new list for each pair of key points. Make sure you don't modify the list after putting it as a key into the map. (You can wrap it by Collections.unmodifiableList to make sure of this.)An alternative would be some custom pair-of-points class (with it own hashCode and equals implementation).
当您使用数组作为哈希映射的键时,将使用该数组的 hashCode 方法来确定键的哈希值,而不是您的 Point 类。
对于您的具体情况,我会尝试使用地图的地图:
Map>
或具有 2 个键和一个值的自定义 2D 矩阵类。When you use an array as the key for a hash map it is that array's hashCode method that is used to determine the key's hash and not your Point class.
For your specific case I would try using a map of maps:
Map<Point, Map<Point, Double>>
or a custom 2D matrix class with 2 keys and a value.