Setting own class as key in java Hashmap

2020-01-29 06:35发布

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 ?

标签: java hashmap
8条回答
别忘想泡老子
2楼-- · 2020-01-29 06:48

As of java8 you should also implement Comparable (adding compareTo) because if the number of hash clashes exceeds 11, HashMap stores the entries in a binary tree. If you don't, performance suffers

查看更多
不美不萌又怎样
3楼-- · 2020-01-29 06:55

You should implement equals() and hashCode(). Your class should also be immutable. If it is mutable, it's hash code can change after adding it to map. Then the map can have problems finding it.

查看更多
\"骚年 ilove
4楼-- · 2020-01-29 06:57

HashMap doesn't check compareTo();

HashMap checks hashCode() and equals().

查看更多
太酷不给撩
5楼-- · 2020-01-29 07:01

You should implement equals() and hashCode(). Your class should also be immutable. If it is mutable, it's hash code can change after adding it to map. Then the map can have problems finding it.

查看更多
beautiful°
6楼-- · 2020-01-29 07:01

1) In general for collections, what you want to override is the equals() method (and also the hashcode() method) for your class. compareTo()/Comparable and Comparator are typically used for sorting and only take the place of using the equals() method for object equivalance in some cases - examples are implementers of SortedSet such as TreeSet.

2) Please conform to Java naming standards in your code. Your class names should be capitalized... e.g new MyKey(dummyArguments). See http://www.oracle.com/technetwork/java/codeconventions-135099.html#367 (and http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) for more detail.

查看更多
老娘就宠你
7楼-- · 2020-01-29 07:03

You need to implement hashCode() and equals(). compareTo() is additionally required for sorted map/set.

See this question for details.

查看更多
登录 后发表回答