对放入HashMap中的元素会自动拆箱。会把Integer转换成int基本数据类型。 HashMap<String, Integer> words = new HashMap<String, Integer>(1000); public int get(String word){ return words.get(word); //如果word没找到,就抛出异常 } 修改get方法: public int get(String word){ Integer freq = words.get(word); if(freq==null) //需要判断空值 return 1; return freq; }
本文介绍了在使用HashMap时,如何将Integer类型的值自动转换为int基本数据类型的过程,并提供了具体的代码示例。此外,还讨论了如何正确处理get方法中可能出现的空值情况。
1万+

被折叠的 条评论
为什么被折叠?



