不适用于参数排序错误

Not applicable for the arguments sorting error

我尝试排序,但出现编译错误

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (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();
    }
}

那是我的竞争对手:

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);
    }
}

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

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

如果您打算比较 Map.EntryList 的值,您应该 告诉比较器 :

 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);
  }
 }