定义Map时候 记得把类型写在定义的后面:在初始化时候写类型不好使
Map map = new HashMap<Integer, Integer>(); for(int i=0;i< nums.length;i++){ if(map.containsKey(nums[i])){ //下一行会报错:Operator '+' cannot be applied to 'java.lang.Object', 'int' int newValue= map.get(nums[i])+1;//这一行会报错:Operator '+' cannot be applied to 'java.lang.Object', 'int' //上一行会报错:Operator '+' cannot be applied to 'java.lang.Object', 'int' map.put(nums[i],newValue); }else { map.put(nums[i],1); } }
正确写法:
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i< nums.length;i++){ if(map.containsKey(nums[i])){ int newValue= map.get(nums[i])+1; map.put(nums[i],newValue); }else { map.put(nums[i],1); } }