Reputation: 1015
I have this String to String map, and I am trying to pass char
as a key
Map<String, String> phone = new HashMap<String, String>() {{
put("2", "abc");
put("3", "def");
put("4", "ghi");
put("5", "jkl");
put("6", "mno");
put("7", "pqrs");
put("8", "tuv");
put("9", "wxyz");
}};
String letterList = phone.get('2'); //null
String letterList = phone.get(String.valueOf('2')); //it works
Why does the first case not work? In my understanding, char
can be implicitly converted to String "2", and HashMap use equals()
to compare keys, so that it should retrieve the key in map?
Upvotes: 1
Views: 465
Reputation: 5061
java.util.Map
uses Objects only as a key so whenever you do map.get('c')
since c is a char the compiler will do autoboxing operation parsing the char c primitive into Character
Object (not String as you thought)
So at the end compiler will parse the following:
map.get('2')
into > map.get(Character.valueOf('2'))
And since Character.valueOf('2')
key does not exist in your map null is returned
Upvotes: 2
Reputation: 83527
Why does the first case not work? In my understanding, char can be implicitly converted to String "2"
Your understanding is incorrect. A char
will not be implicitly converted to String
. If you look at the documentation, you will see this method get(Object key)
. I don't know why this isn't get(K key)
instead. However, this explains why your first example compiles without any errors: the char
constant is autoboxed into a Character
object. Since the Character
with the value '2'
is not a key in your Map
, get()
returns null
.
Upvotes: 5