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?
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
.