读书人

map.contains( )小疑点

发布时间: 2012-06-01 16:46:36 作者: rapoo

map.contains( )小问题,在线等
下面的代码用于输出字符数组ch中每个字符出现的次数,应该填入的

代码是
public static void main(String[] args) {
char[] ch = { 'a', 'c', 'a', 'b', 'c', 'b' };
HashMap map = new HashMap();
for (int i = 0; i < ch.length; i++) {
< 填入代码 >
}
System.out.println(map);
}

A.if (map.contains(ch[i])) {
map.put(ch[i], map.get(ch[i]) + 1);
} else {
map.put(ch[i], 1);
}

B.if (map.contains(ch[i])) {
map.put(ch[i], (Integer) map.get(ch[i]) + 1);
} else {
map.put(ch[i], 1);
}

C.if (map.containsKey(ch[i])) {
map.put(ch[i], (int) map.get(ch[i]) + 1);
} else {
map.put(ch[i], 1);
}

D.if (map.containsKey(ch[i])) {
map.put(ch[i], (Integer) map.get(ch[i]) + 1);
} else {
map.put(ch[i], 1);
}

正确答案:D
问:为什么其它的三个选项不行呢,thanks

[解决办法]
首先HashMap没有contains方法,排除A和B
另外C中map.get(ch[i])返回时Object型无法转成int型,只能转其封装类Integer,
所以选D
[解决办法]

探讨
首先HashMap没有contains方法,排除A和B
另外C中map.get(ch[i])返回时Object型无法转成int型,只能转其封装类Integer,
所以选D

[解决办法]
1楼正解
[解决办法]
探讨

首先HashMap没有contains方法,排除A和B
另外C中map.get(ch[i])返回时Object型无法转成int型,只能转其封装类Integer,
所以选D

读书人网 >J2SE开发

热点推荐