java集合排序的绑定不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19196393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bound mismatch for java Collections sorting
提问by nilkash
Hi need Help regarding java collection sorting. It gives me this error:
您好需要有关 Java 集合排序的帮助。它给了我这个错误:
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<WifiSSID>).
The inferred type WifiSSID is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>
My code looks like:
我的代码看起来像:
public class WifiSSID {
public String SSIS;
public double id;
}
public class ScanFilterWifiList {
public ScanFilterWifiList(List<WifiSSID> wifiList) {
Collections.sort(wifiList);
//Collections.sort(wifiList, new SortSSIDByid()); tried this also.
}
}
interface Comparator<WifiSSID>
{
int compare(WifiSSID obj1, WifiSSID obj2);
}
class SortSSIDByid implements Comparator<WifiSSID>
{
@Override
public int compare(WifiSSID ssid1, WifiSSID ssid2)
{
int value = 0;
if (ssid1.id > ssid2.id)
value = 1;
else if (ssid1.id < ssid2.id)
value = -1;
else if (ssid1.id == ssid2.id)
value = 0;
return value;
}
}
Am I doing anything wrong?
我做错了什么吗?
采纳答案by JB Nizet
You can't sort a List of objects that don't implement the Comparable
interface. Or rather, you can, but you have to provide a Comparator
to the Collections.sort()
method.
您无法对未实现Comparable
接口的对象列表进行排序。或者更确切地说,您可以,但您必须Comparator
为该Collections.sort()
方法提供 a 。
Think about it: how would Collections.sort()
sort your list without knowing when a WifiSSID is smaller or bigger than another one?
想一想:Collections.sort()
在不知道 WifiSSID 何时比另一个小或大的情况下,如何对您的列表进行排序?
You want to use Collections.sort(wifiList, new SortSSIDByid());
你想用 Collections.sort(wifiList, new SortSSIDByid());
EDIT:
编辑:
You defined your own proprietary Comparator
interface, and implement this proprietary Comparator interface in SortSSIDByid
. Collections.sort()
wants an intance of java.util.Comparator
. Not an instance of your proprietary Comparator interface, that it doesn't know.
您定义了自己的专有Comparator
接口,并在SortSSIDByid
. Collections.sort()
想要一个java.util.Comparator
. 不是您的专有 Comparator 接口的实例,它不知道。
回答by SudoRahul
Just add this import import java.util.Comparator;
只需添加此导入 import java.util.Comparator;
and remove this interface
并删除此接口
interface Comparator<WifiSSID>
{
int compare(WifiSSID obj1, WifiSSID obj2);
}
Your SortSSIDByid
comparator class will now implement java.util.Comparator
and that is what is required by the Collections.sort()
method.
您的SortSSIDByid
比较器类现在将实现java.util.Comparator
,这就是该Collections.sort()
方法所需要的。