不适用于参数排序错误

时间:2015-12-19 15:21:56

标签: java sorting comparator

我尝试排序但是我收到了编译错误

  

sort(List<T>, Comparator<? super T>)类型中的方法Collections不适用于参数(List<Map.Entry<T,Integer>>, HashMapHistogramComparator<T>)

这是我的代码:

public class HashMapHistogramIterator<T> implements Iterator<T> {
    private List<HashMap.Entry<T,Integer>> items;
    Iterator<HashMap.Entry<T,Integer>> lst;

    public HashMapHistogramIterator(HashMapHistogram<T> hshMp) {
        this.items = new ArrayList<HashMap.Entry<T,Integer>>();
        this.items.addAll(hshMp.getAllMap());
        Collections.sort(this.items, new HashMapHistogramComparator<T>(hshMp));
        this.lst = this.items.iterator();
    }
}

这就是我的comperator:

import java.util.Comparator;

public class HashMapHistogramComparator<T> implements Comparator<T>{
    HashMapHistogram<T> hshMp;

    public HashMapHistogramComparator(HashMapHistogram<T> hshMp){
        this.hshMp = hshMp;
    }

    @Override
    public int compare(T arg0, T arg1) {
        int val1 = this.hshMp.getValue(arg0);
        int val2 = this.hshMp.getValue(arg1);
        return Integer.compare(val2,val1);
    }
}

1 个答案:

答案 0 :(得分:0)

当您比较 T时,您的this.items可能是错误的类型:

   this.items = new ArrayList<T>();
   this.items.addAll(hshMp.keySet());

如果您要将List Map.Entry的{​​{1}}与其值进行比较,则应该告诉比较者

 HashMapHistogramComparator<T> implements Comparator<HashMap.Entry<T,Integer>> {
  HashMapHistogram<T> hshMp;

  public HashMapHistogramComparator(HashMapHistogram<T> hshMp){
    this.hshMp = hshMp;
  }

  @Override
  public int compare(HashMap.Entry<T,Integer> arg0, HashMap.Entry<T,Integer> arg1) {
    int val1 = arg0.getValue();
    int val2 = arg1.getValue();
    return Integer.compare(val2,val1);
  }
 }