如何从数组中获取最常见的met字符(Generics)

时间:2015-04-03 21:52:15

标签: java

假设(new Integer[]{10,10,20,10,20,30,10,20,30,40,50,10,20,30,40,50,60})传递给方法public static <T> Pair<T, Integer> mode(T items[])。该方法应返回10, 5(数组中有五个数字10).S,基本上该方法返回数组中最常用的元素。我该如何完成这种方法?请不要MAPSCOLLECTIONSHashSets,仅ArrayLists

      import java.util.ArrayList;

public class Mode {

    public static <T> Pair<T, Integer> mode(T items[])
    {
        ArrayList <Pair<T, Integer>> temp = new ArrayList<>();
        //ArrayList <T> temp = new ArrayList<>();

        for(T values: items)
        {
            temp.add((Pair<T, Integer>) values);
        }

        for(int i = 0; i < temp.size(); i++)
            for(int j = 0; j < temp.size(); j++)
        {
            if(temp.get(i) == temp.get(j))
        }
    }
}


    public class Pair<X,Y>{
      private X first;
      private Y second;

      public Pair(X x, Y y){
        this.first = x;
        this.second = y;
      }

      public X getFirst(){
        return this.first;
      }
      public Y getSecond(){
        return this.second;
      }

      public boolean equals(Object o){
        if(!(o instanceof Pair)){
          return false;
        }
        Pair p = (Pair) o;
        return
          this.first.equals(p.first) &&
          this.second.equals(p.second);
      }

      public String toString(){
        return String.format("(%s,%s)",first,second);
      }

    }

1 个答案:

答案 0 :(得分:0)

迈克,请尝试以下方法:

import java.util.ArrayList;
public class Mode {

public static Pair<T, Integer> mode(T[] a)
 {

    int count = 1, tempCount;
    T popular = a[0];
    T temp;
    for (int i = 0; i < (a.length - 1); i++)
    {
        temp = a[i];
        tempCount = 1;
        for (int j = 1; j < a.length; j++)
        {
          if (temp.equals(a[j]))
            tempCount++;
        }
        if (tempCount > count)
        {
          popular = temp;
          count = tempCount;
        }
      }
      return new Pair(popular, new Integer(count));
        }
    }


public class Pair<X,Y>{
  private X first;
  private Y second;

  public Pair(X x, Y y){
    this.first = x;
    this.second = y;
  }

  public X getFirst(){
    return this.first;
  }
  public Y getSecond(){
    return this.second;
  }

  public boolean equals(Object o){
    if(!(o instanceof Pair)){
      return false;
    }
    Pair p = (Pair) o;
    return
      this.first.equals(p.first) &&
      this.second.equals(p.second);
  }

  public String toString(){
    return String.format("(%s,%s)",first,second);
  }

}

如果您有任何疑问,请与我们联系。