[英]How to sort a Collection of generic Pairs
這是家庭作業,因此我希望提供一些解釋,而不僅僅是給我答案。
我有一個通用的Pair類,可以接受任何鍵值K和任何值V。
目的是編寫一個通用方法:
public static <...> Collection<Pair<...>> sortPairCollection(Collection <Pair<....>> col)
唯一的其他准則是K類型必須實現Comparable <...>。
經過一番挖掘,我看到人們推薦這樣的東西:
public static Collection<Pair<?,?>> sortPairCollection(Collection<Pair<?,?>> col)
{
Collections.sort(col, new Comparator<Pair<?,?>>(){
@Override
public int compare(Pair<?, ?> x, Pair<?, ?> y) {
return (Integer)x.v() - (Integer)y.v();
}
});
}
但這對我不起作用,我收到一條錯誤消息,指出sort方法不適用於那些參數。 我真的不知道從這里去哪里。
Collections.sort
僅適用於List
實例,不適用於常規Collections
。 例如,對HashSet
進行排序沒有任何意義。
其次,由於算術溢出,應避免在類似的比較器中使用減法。 最好使用Integer.compare
。
同樣,返回類型為Collection<Pair<?,?>>
必須返回某些內容。 您可以返回col
,但是在對col
進行突變時,使該方法void
更有意義。
另一點是,除非第二個類型參數為Integer
(我假設v()
返回類型為V
),否則您的方法似乎將拋出ClassCastException
。 在這種情況下,沒有必要為Pair<?, ?>
編寫方法,因為您可以只使用Pair<?, Integer>
。
最后,由於泛型在Java中的工作方式,您實際上將無法使用當前簽名傳遞List<Pair<String, Integer>>
,因為List<Pair<String, Integer>>
不是 List<Pair<?, Integer>>
(請參閱此問題或該 問題 )。 如果要執行此操作,則參數應具有List<? extends Pair<?, Integer>>
類型List<? extends Pair<?, Integer>>
List<? extends Pair<?, Integer>>
。
編輯
我現在意識到我還沒有真正回答這個問題。 這個想法不是改變原始的集合,而是返回一個新的集合。 此外,排序還應該通過鍵而不是值進行,因為K
必須實現Comparable
。
為了使用compareTo
方法,您需要指出K extends Comparable
。 這樣做的方法是使用簽名
public static <K extends Comparable<? super K>, V> Collection<Pair<K, V>> sortPairCollection(Collection<Pair<K, V>> col)
這有點麻煩-泛型已大大增加了方法簽名的復雜性。
K extends Comparable<? super K>
K extends Comparable<? super K>
說K
S可與其它相比較K
秒。
不過,您仍然需要使用List
。 您可以使用接受Collection
的ArrayList
構造函數。
根據要求,我將由您自行編寫正確的代碼。
這是完整的程序:
public static <K extends Comparable<? super K>, V extends Comparable<? super V>> void sortPairCollection(List<Pair<K, V>> col){
Collections.sort(col, new Comparator<Pair<K,V>>(){
public int compare(Pair<K, V> o1, Pair<K, V> o2) {
int keyflag = o1.getValue().compareTo(o2.getValue()) == 0 ? o1.getKey().compareTo(o2.getKey()): o1.getValue().compareTo(o2.getValue()) ;
return keyflag;
}});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.