没人理我,看得到源码吗?
import java.util.*;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++) {
      // Produce a number between 0 and 20:
      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.println(hm);
  }

解决方案 »

  1.   

    使用HashSet来装入Counter对象,并比较Counter的i值,如i值相同则不装入,且i值加1;
      

  2.   

    也就是用HashSet(而非源码中的HashMap)来实现同样的功能!
      

  3.   

    class Counter { 
      int i = 1; 
      public String toString() { 
        return Integer.toString(i);
      }
       public boolean equals(Object obj)
    {
    if (obj != null)
    {
    if (this.getClass().equals(obj.getClass()))
    {
    Counter that = (Counter) obj;
    return (this.i == that.i);
    }
    }
    return false;
    }
    public int hashCode()
    {
    return (i+"").hashCode();
    }
    }
      

  4.   

    import java.util.*;
    import java.io.*;class Counter {
      int i = 1;
      public String toString() {
        return Integer.toString(i);
      }
    }
    public class testH {  public testH() {
      }
      public static void main(String[] args) {
        testH testH1 = new testH();
        //HashMap hm = new HashMap();
        HashSet hm=new HashSet();
        HashMap hp=new HashMap();
        for(int i = 0; i < 10000; i++) {
          // Produce a number between 0 and 20:
          Integer r = new Integer((int)(Math.random() * 20));
          if(!hm.contains(r))
            hm.add(r);
        }
        System.out.println(hm);
      }}
      

  5.   

    import java.util.*;class Counter {
      int i = 1;  public Counter(int i) {
        this.i = i;
      }
      public String toString() {
        return Integer.toString(i);
      }  public boolean equals(Object o) {
        return ((o instanceof Counter) && (((Counter)o).i == i));
      }  public int hashCode() {
        return i;
      }
    }public class Statistics {
      public static void main(String[] args) {
        HashSet hs = new HashSet();
        for(int i = 0; i < 10000; i++) {
          // Produce a number between 0 and 20:
          Counter counter = new Counter((int)(Math.random() * 20));
          if(hs.contains(counter)) {
            //无法内部计数,因为HashSet没有直接的方法去获得包含的对象,它主要是排序,方便搜寻
          }
          else {
            hs.add(counter);
          }
        }
        System.out.println(hs);
      }
    }