Set your own class as the key in Java HashMap

I have a class that I want to set as a key in HashMap I have implemented the CompareTo method of this class But when I do

map.put(new MyKey(dummyArguements),dummyValue );
System.out.println(map.get( new MyKey(dummyArguements) ) );

I'm empty @ h_ 419_ 5 @ so this means that HashMap cannot recognize that the two keys (for get & put calls) are the same

Can someone help me

Solution

You need to implement hashcode () and equals () CompareTo () is also required for sorted mappings / collections

See this question for details

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>