以下程序如何理解?
public class counter {
    int i=1;
    public String toString(){
        return Integer.toString(i);
    }
}
public class statistics {
    public static void main(String[] args) {
      HashMap hm=new HashMap();
      for(int i=0;i<10000;i++){
          Integer r=new Integer((int)(Math.random()*20));
          if(hm.containsKey((r)))
              ((counter)hm.get(r)).i++;
          else
              hm.put(r,new counter());
      }
      System.out.print(hm);       
    }
}

解决方案 »

  1.   

    统计一万次随机产生的0到20之间的数产生的次数
    for(int i=0;i <10000;i++){ //产生10000个随机数范围在0到20之间
       Integer r=new Integer((int)(Math.random()*20)); 

    if(hm.containsKey((r))) 
                  ((counter)hm.get(r)).i++; 
              else 
                  hm.put(r,new counter()); 
          } 
    是判断产生的随机数有没有在HashMap中,在则把其数量加1,不在把该数放入到HashMap中。
    System.out.print(hm); //输出结果
      

  2.   

    以下程序如何理解? 
    public class counter { //定义统计类
        int i=1;    //定义变量I并赋值
        public String toString(){   //重写OBJECT的toString方法
            return Integer.toString(i);    //当调用对象的toString方法时输出I
        } 

    public class statistics {    //定义主类
        public static void main(String[] args) { //主方法
          HashMap hm=new HashMap();    //新建一个阿希表
          for(int i=0;i <10000;i++){   //循环一万次
              Integer r=new Integer((int)(Math.random()*20));  //新建一个随机数
              if(hm.containsKey((r)))    //如果表中以经存在这个数作为关键字的对象
                  ((counter)hm.get(r)).i++;  //那么将表中的这个对象的统计属性加一
              else 
                  hm.put(r,new counter());  //如果不存在则以这个数为关键字新建一个统计对象存入表
          } 
          System.out.print(hm);  //输出哈希表        
        } 
    }
    这个程序的大体功能是统计产生一万个小于20的随机数的时候会有多少重复数,是那些数.各重复了多少次