I believe I can fly

虫虫的Blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  8 随笔 :: 2 文章 :: 2 评论 :: 0 Trackbacks
今天在使用MAP时,用了泛型,但是编译时报了一个错,开始感到很纳闷,源代码如下:
import java.util.*;

public class TestMap2{
    
private static final Integer ONE = new Integer(1);
    
    
public static void main(String[] args){
        Map
<String> m = new HashMap<String>();
        
for(int i = 0; i < args.length; i++){
            Integer freq 
= m.get(args[i]);
            m.put(args[i],(freq 
== null ? ONE : new Integer(freq.intValue() + 1)));
            }

            
        System.out.println(m.size() 
+ "distinct words detected!");
        System.out.println(m);
        }

    }
编译时报错为:类型变量数目错误,需要2
开始感到很奇怪,查了API才发现MAP的泛型用法错误,正确的用法应该是下面这样的:
import java.util.*;

public class TestMap2{
    
private static final Integer ONE = new Integer(1);
    
    
public static void main(String[] args){
        Map
<String,Integer> m = new HashMap<String,Integer>();
        
for(int i = 0; i < args.length; i++){
            Integer freq 
= m.get(args[i]);
            m.put(args[i],(freq 
== null ? ONE : new Integer(freq.intValue() + 1)));
            }

            
        System.out.println(m.size() 
+ "distinct words detected!");
        System.out.println(m);
        }

    }

这时,编译就没问题了!

QQ交流群:90623790
posted on 2009-04-14 23:42 虫虫 阅读(3484) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: