在java Hashmap中将自己的类设置为键 [英] Setting own class as key in java Hashmap
本文介绍了在java Hashmap中将自己的类设置为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类,我想将其设置为 HashMap 中的键.我已经为该类实现了 compareTo 方法.但是当我这样做时:
<上一页>map.put(new MyKey(dummyArguements) , dummyValue );System.out.println(map.get( new MyKey(dummyArguements) ) );我得到空值.所以这意味着 hashmap 无法识别这两个键(用于 get 和 put 调用)是相同的.
有人可以帮我吗?
解决方案
需要实现hashCode()
和equals()
.compareTo()
对于有序的地图/集合是额外需要的.
有关详细信息,请参阅此问题.
I have a class which I want to set up as keys in HashMap. I already have implemented the compareTo method for that class. But still when I do:
map.put(new MyKey(dummyArguements) , dummyValue ); System.out.println(map.get( new MyKey(dummyArguements) ) );
I get null. So that means hashmap is not able to identify that the two keys (for get & put call) are same.
Could someone help me here please ?
解决方案
You need to implement hashCode()
and equals()
. compareTo()
is additionally required for sorted map/set.
See this question for details.
这篇关于在java Hashmap中将自己的类设置为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文