String as Key in HashMap

I saw that only String is used as a key in the HashMap. Although the put () method takes an Object as a parameter. What value does it have. If any other object can also be used as a key or not? Please provide answers.

+3
source share
6 answers

Any object that provides meaningful implementation hashCode()is an ideal key candidate on the map: see Understanding the work of equals and hashCode in a HashMap .

In addition, as @Jon mentioned, all keys on your card must be of the same type.

EDIT: , equals(), hashCode(). , . hashCode() HashMap, .

EDIT2: @Adrian , .

:

+8

HashMap . , , ,

Map<String, Whatever> map = new HashMap<String, Whatever>();

, put() .

 

NB: , , equals, hashCode !

+6

, , "String" -, , .

,
, , ( 15 " Java", 2- )

+3

, String HashMap, , String Java, String -, String Java - , hashcode String, , HashMap.

+1

, , , Java.

HashMap, , , , . , URI :

HashMap<URI, Integer> hitCountMap = new HashMap<URI, Integer>();

get Object , , , , . . .

0

, ( ) Object. , equals(Object) hashcode() , . , equals(Object) HashMap / .

However, if you really need to use Object as a key type, IdentityHashMap might be a better option. For starters, it does not use equals(Object)or hashcode(), but uses the values ==and hash values ​​of the identifiers of key objects.

0
source

Source: https://habr.com/ru/post/1725523/


All Articles