我被要求創建一個toArray
方法,它應該分別返回一個Iterator或數組,其中的元素按照它們的「add」計數(HashMap中的值)以升序排序訂購。在類型集合通用數據結構上的Collections.sort()不起作用
的方法排序(名單< T>,比較<超級T>?)是:
不過,我收到以下錯誤消息,不知道如何解決它不適用的參數(設置<的Map.Entry < T,整數>>,新的比較<的Map.Entry < T,整數>>(){})
所以好像我要重寫或創建排序方法。有人能幫助我指出正確的方向嗎?
public class OccurenceSet<T> implements Set<T>{
private HashMap<T,Integer> data;
public OccurenceSet(){
this.data = new HashMap<T,Integer>();
}
@Override
public Object[] toArray() {
Set<Map.Entry<T,Integer>> dataSet = data.entrySet();
ArrayList<Map.Entry<T,Integer>> dataList = new ArrayList<>(dataSet);
Collections.sort(dataSet, new Comparator<Map.Entry<T,Integer>>() {
@Override
public int compare(Map.Entry<T,Integer> o1, Map.Entry<T, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
return null;
}
}
Collections.sort sorts列出,而不是集合。常規集沒有訂單。 – Eran
嘗試Collections.sort(dataList ... – user7294900