【问题标题】:Not applicable for the arguments sorting error不适用于参数排序错误
【发布时间】:2015-12-19 15:21:56
【问题描述】:

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

Collections 类型中的方法sort(List<T>, Comparator<? super T>) 不适用于参数(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);
    }
}

【问题讨论】:

  • 如果你想排序HashMap.Entry,那么你的比较器应该是class HashMapHistogramComparator&lt;T&gt; implements Comparator&lt;HashMap.Entry&lt;T,Integer&gt;&gt;

标签: java sorting comparator


【解决方案1】:

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

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

如果您打算通过它们的值比较ListMap.Entry,您应该告诉比较器

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

【讨论】:

  • 我需要它有键和值,而不是按值排序
  • 我刚刚看到我只需要返回密钥,所以我不关心列表中的值所以第一件事起作用了谢谢!
猜你喜欢
  • 2013-12-25
  • 2023-03-18
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 2021-11-03
  • 1970-01-01
相关资源
最近更新 更多