当前位置: 代码迷 >> J2SE >> map.contains( )小疑点
  详细解决方案

map.contains( )小疑点

热度:41   发布时间:2016-04-24 00:54:21.0
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
  相关解决方案